Thursday 15 July 2010

bash - How to append a character from a filename to the end of each line of a file from a terminal? -



bash - How to append a character from a filename to the end of each line of a file from a terminal? -

i know how using python, i'd larn how awk or sed or whatever best command line method. have file names

a1.txt a2.txt ... b99.txt b100.txt

each file contains 1 line. i'd append letter in file name end of line. contents of files like:

a 1 file contents a 2 file contents ... b 90 9 file contents b b 1 hundred file contents b

if want alter files in place, sed's -i alternative handy:

for f in *.txt; ltr=${f:0:1}; sed -i "s/$/ $ltr/" "$f" ; done

explanation:

for f in *.txt

this starts loop on .txt files in current directory.

ltr=${f:0:1}

this extracts first character file name

sed -i "s/$/ $ltr/" "$f"

this replaces end of each line in file named f space , first character of file name. in more detail:

-i tells sed create changes in place.

s/$/ $ltr/ substitute command. format s/old/new/ where, here, old $ matches @ end of line, , new $ltr space , first character of file's name.

"$f" tells sed top operate of file named f.

bash awk sed

No comments:

Post a Comment