0

I need to add a word before the line starts, but I want to do that for every line which the text has.

If I have sample/text/ and I want to add data/sample/txt, how can I do that?

I have tried sed i command in several ways but none of it works.

  • 1
    Please show us what command did you try and What are your input and desired output? – cuonglm May 11 '15 at 11:14
  • I have used: sed -i '1 i\data' samples.new.txt and sed -i -e '1idata\' samples.new.txt – E.M.L May 11 '15 at 11:56
  • I would like to get data/sample/text rather than sample/text that I have now.. – E.M.L May 11 '15 at 11:57
  • sed's command i \ is meant for inserting text with embedded newlines. – lcd047 May 11 '15 at 14:46
1

Using sed you can substitute the beginning of a line with 's[^sample/text[data/sample/text[g'

The ^ denotes the start of a line.

The substitute command allowes you to use a different character to seperate the options from the default / to, in this case, [ which is sometimes handy if you have the / character in your search or replacement text.

Before you use the -i flag to perform the inline replacement, first try this on a file and redirect it's output to see if it has the desired output.

  • Thank you for your comment. Unfortunately this won't work again.. – E.M.L May 11 '15 at 11:59
  • I just changed something and it worked, thank you so much! – E.M.L May 11 '15 at 12:05
  • +1 but that's a strange choice for a delimiter. – glenn jackman May 11 '15 at 13:55
  • Plus consider using & in the replacement (DRY): s[^sample/text[data/&['. Note that you're anchoring the expression, so no point in using the g` flag -- it can match at most once. – glenn jackman May 11 '15 at 14:08
0

Use AWK.

If your file is textfile and you want to add the text newtext to every line you can use:

 awk '{print "newtext ",$0}' textfile

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.