Search code examples
linuxsednewlinelinefeed

sed read single line without linefeed


As a novice linux user, I try to use sed to replace some text string. The new string is the content of a line of another file's. It basically works as intended apart from that a newline is inserted after the substituted text (which I dont want :-)

newString=`sed -n "$(($line+1))"p otherFile `
sed "s@oldString@$newString@" < oldFile > newFile

I unsuccessfully tried to remove a potential LF within newString (using different approaches I found online, among others the popular sed ':a;N;$!ba;s/\n/ /g' ) before I applied sed s.

Right now it only looks like as follows:

Some text to be replaced

turns e.g. into

Some text is
replaced

while I would like to have a single line result only. I guess the problem lies in the newString being read as a whole line via sed -n p. If I define manually a newString the substitute works as desired to produce a single line only.


Solution

  • sed will always terminate its output with a newline (albeit process substitution normally strips the last newline, so I'm not sure why you see this problem).

    You can modify your variable afterwards (assuming your shell is Bash):

    newString="${newString%%$'\n'}"
    

    Demonstration:

    $ s=$'abc\n'
    $ printf '>> %q <<\n' "$s" "${s%%$'\n'}"
    >> $'abc\n' <<
    >> abc <<