0

I have a text file, itemlist.txt, which is comprised of a list of strings like so:

Item1
Item2
Item3
Item4
...

Each string corresponds to a text file (all with the same file extension) in the same directory as the list. In other words, Item1 in the list signifies Item1.txt in the same directory, and so forth.

What is an efficient method to use this list to edit each file, appending the filename of each file to itself using a Bash shell script? In other words, "Item1" should be the last line of Item1.txt, etc.

I have GUI-based workflow tools to further manipulate these text files once the strings are in place, but I have a LOT to learn about Bash and this has stumped me. Ideally I would like to write a script that accepts user-defined arguments to write to the files along with the filename, but... baby steps!

I think sed is better for this than echo, in terms of manipulating the text files, but I am having trouble looping through the text file properly.

codeforester
  • 39,467
  • 16
  • 112
  • 140

2 Answers2

3

echo is probably the easiest since you want to append

while read f; do
    echo "$f" >>"$f.txt"
done <itemlist.txt
krayon
  • 96
  • 5
2

You can use a simple read loop for this:

while read -r item; do
  file="$item.txt"
  [[ ! -f "$file" ]] && continue # skip if file doesn't exist or if it is not a regular file
  printf '%s\n' "$item" >> "$file"
done < itmelist.txt
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • This works well in the general case with test data. When I apply it to my specific case, I run into an issue (I think) because the actual text files are named such that line 2 needs to look like `file="$item_foo.txt"' where foo is the same for the whole batch. However, this code doesn't work (I guess the underscore needs to be escaped?). If I add '_foo' to the end of an item in the text file, it works. – Greg Smith Mar 23 '17 at 18:31
  • `file="${item}_foo.txt"` would do it. – codeforester Mar 23 '17 at 18:33
  • It certainly does! – Greg Smith Mar 23 '17 at 18:35
  • Great. `"$item\_foo.txt"` wouldn't work because `_` has no special meaning to shell and trying to escape it would result in literal `\_`. – codeforester Mar 23 '17 at 18:38
  • In case anyone finds the code here useful for their own work, note that you may run into the issue described here: http://stackoverflow.com/questions/12916352/shell-script-read-missing-last-line if your itemlist.txt file does not end with a newline. The solution there worked perfectly for me. – Greg Smith Mar 23 '17 at 18:57