Add prefix and suffix to every line in a .txt file

I am trying to append and prepend text to every line in a .txt file.

I want to prepend: I am a

I want to append: 128... [}

to every line.

Inside of a.txt:

fruit, like
bike, like
dino, like

Upon performing the following command:

$ cat a.txt|sed 'I am a ',' 128... [}'

it does not work how I want it to. I would really want it to say the following:

I am a fruit, like 128... [}
I am a bike, like 128... [}
I am a dino, like 128... [}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Simple sed approach:

sed 's/^/I am a /; s/$/ 128... [}/' file.txt
  • ^ – stands for start of the string/line
  • $ – stands for end of the string/line

The output:

I am a fruit, like 128... [}
I am a bike, like 128... [}
I am a dino, like 128... [}

Alternatively, with Awk you could do:

awk '{ print "I am a", $0, "128... [}" }' file.txt

Method 2

sed 's/.*/PREFIX&SUFFIX/' infile

will do, assuming PREFIX and SUFFIX don’t contain any special characters.


&/ (backslash, ampersand and delimiter) are special when in the right hand side of a substitution. The special meaning of those characters can be suppressed by escaping them (preceding them by a backslash) e.g. to prepend A//BC and to append XYZ&& one would run:

sed 's/.*/A//BC&XY\Z&&/' infile

Method 3

Perl:

$ perl -lne 'print "I am a $_ 128... [}"' file 
I am a fruit, like 128... [}
I am a bike, like 128... [}
I am a dino, like 128... [}

More Perl:

$ perl -pe 's/^/I am a /; s/$/ 128... [}/' file 
I am a fruit, like 128... [}
I am a bike, like 128... [}
I am a dino, like 128... [}

And a bit more Perl:

$ perl -lpe '$_="I am a $_ 128... [}"' file 
I am a fruit, like 128... [}
I am a bike, like 128... [}
I am a dino, like 128... [}

For all of these, you can use -i to make the change in the original file:

$ perl -i -lne 'print "I am a $_ 128... [}"' file 
$ perl -i -pe 's/^/I am a /; s/$/ 128... [}/' file 
$ perl -i -lpe '$_="I am a $_ 128... [}"' file

Method 4

Alternative sed

sed -e 's/^(.*)$/I am a 1 128 [{/

It searches for everything .* between the start ^, and end of line $, and places it in a group ( ). It then replaces it with the prefix, the (first) group 1, and the suffix.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x