I have a bash script which has a variable being set from the output of cat and grep:

result=`cat $file | grep -A2 "$search"`

result contains 3 lines E.G.:

This is Line 1
This is line 2
This is line 3

I need to prefix each line with a space:

 This is Line 1
 This is line 2
 This is line 3

I have tried the following:

result=`echo $result | awk '{print " "$0}'`

and a few different sed commands, all of which result in this:

 This is Line 1 This is line 2 This is line 3

they add the spaces, but delete the new lines

Note: this will be saved into a file which needs the line breaks

  • < $file grep -A2 "$search" | sed -e 's/^/ /'. If you want to use the text captured in $result then <<< "$result" sed -e 's/^/ /'. echo converts newlines to spaces. – AlexP Nov 17 '17 at 10:54
  • 3
  • Dear @steeldriver, Yes, correct for the last part of OP's question which s/he wants to have newlines intact, the duplicated question as you flagged is right duplicate, but here OP wants to add a space for each line which is the main challenge and his question. – αғsнιη Nov 17 '17 at 11:57
  • 1
    @αғsнιη the OP seems to have solved the "main challenge" (although personally I would have used sed rather than awk); their code should work fine if they simply quote $result to prevent word splitting by the shell i.e. echo "$result" | awk '{print " "$0}' – steeldriver Nov 17 '17 at 14:31
  • Voting to leave open - this is a much more specific use case while the linked question gives a highly general answer that doesn't help with the user's immediate problem. – Shadur Nov 20 '17 at 9:26


awk '{printf " %s\n",$0}' file-in.txt > file-out.txt


sed -e 's/^/ /' file-in.txt > file-out.txt

sed (same file)

sed -i -s 's/^/ /' file.txt

Use awk at first start instead of using grep and stop going to extra processing on $result (This is a kind of grep's -A Num simulation).

result=$(awk -v patt="$search" '$0 ~ patt{S=1}
         S && ($0 ~ patt || ++n<3) {print " "$0} n==3{n=0}' infile)

Then print/save the $result into a output file:

printf '%s\n' "$result" > outfile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.