2

I have a text file (1.txt) as follows:

word1
word2
word3

I use sed to add strings to the beginning and end of every line as follows:

sed 's/^/blahblah1  /g' 1.txt > 2.txt
sed 's/$/  blahblah2/g' 2.txt > 3.txt

resulting in:

blahblah1  word1  blahblah2
blahblah1  word2  blahblah2
blahblah1  word3  blahblah2

This works fine, but I want to do something further.

I want to copy the strings in the middle of each line (word1, word2, etc.) to the end of every line as follows:

blahblah1  word1  blahblah2 word1
blahblah1  word2  blahblah2 word2
blahblah1  word3  blahblah2 word3

PLEASE NOTE that blahblah1 and blahblah2 are just representing bash commands and other string text AND are the same at the beginning and end of every line as the sed commands illustrate – the strings between them are DIFFERENT – and the strings are not actually "blahblah1" and "blahblah2".

Any suggestions?

Basically, I'm taking a text file containing a list of strings and want to create a bash script containing a list of commands to grab lines of code containing a string and dump them to files with a file name containing that string – hence the structure of each line.

2
  • 3
    Can't you just do sed 's/.*/blahblah1 & blahblah2 &/' 1.txt? Jan 5, 2017 at 18:41
  • @steeldriver just post it as an answer , it matches up perfectly with what OP's desired output Jan 6, 2017 at 3:10

2 Answers 2

0

EDIT: Just realized this probably doesn't solve your problem, since the following assumes that the "middle word" is the second word.

Try this script. Input is read from file input.txt

while read ln; do
    middle_word=`awk '{print $2}' <<< "$ln"`
    new="$ln $middle_word"
    echo "$new"
done < input.txt

With the input you gave, this gives me the following output:

blahblah1  word1  blahblah2 word1
blahblah1  word2  blahblah2 word2
blahblah1  word3  blahblah2 word3

Caveat: The leading whitespace on each line is lost for some reason.

0

Very simple to achieve with AWK:

$ awk '{print "blah1",$0,"blah2",$0}'    1.txt                                                                           
blah1     word1 blah2     word1
blah1     word2 blah2     word2
blah1     word3 blah2     word3

Or with python:

$ python -c "import sys; print '\n'.join([ ' blah1 ' + l.strip() + ' blah2 ' + l.strip() for l in sys.stdin])" <  1.txt  
 blah1 word1 blah2 word1
 blah1 word2 blah2 word2
 blah1 word3 blah2 word3

In both cases the idea is the same - we read file ( or in python's case,stdin) line by line, and print new strings made up out of what we read.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .