问题
Im trying to understand sed command and loops. I need to take part of the text (20 lines) and append it to the csv with the file name. here is my code
for i in ~/mspl/*.doc
do
catdoc "$i" > auto.txt
sed -e '1,20!d' auto.txt > auto1.txt
sed -e '1s/^/"$i" ;/' auto1.txt > auto2.txt
sed -e '20s/$/~/' auto2.txt > auto3.txt
cat auto3.txt >> lines.csv
done
the problem is that my second "i" argument doesn't convert to the file name in csv.
in the line
sed -e '1s/^/"$i" ;/' auto1.txt > auto2.txt
Please tell what is my mistake here?
回答1:
The issue is that variables are not expanded within single quotes '. Use double quotes instead ":
# this is assuming you did want to add explicit " around your $i
sed -e "1s/^/\"$i\" ;/" auto1.txt > auto2.txt
If your double-quoted string needs to contain explicit double quotes, you have to escape them (\"). If using double quotes is not an option (e.g. if you have a very complex command with multiple levels of quoting already) you can always exit the quoting around your variable:
sed -e '1s/^/"'$i'" ;/' auto1.txt > auto2.txt
回答2:
You might find it useful to run this script with the -x setting, to see what's actually going on. (Just do set -x.)
But just to be blunt, what's going on is that your $i is inside single quotes, so it doesn't get expanded.
来源:https://stackoverflow.com/questions/14402121/arguments-inside-sed-loop