简体   繁体   中英

sed command in ubuntu

I want to find the USB PORT of the device connected to the machine. I used the command

dmseg | grep "ttyUSB" | grep "attached"

I got the output as

[  525.763315] usb 1-1: FTDI USB Serial Device converter now attached to ttyUSB0
[  525.796039] usb 1-1: FTDI USB Serial Device converter now attached to ttyUSB1

But I need the port only. SO I used the command

cut -d ' ' -f14

I got

ttyUSB0
ttyUSB1

I want to replace the value of a file with this output.So i used the se command

sed -i "s/\b\SERIAL_INTERFACE=\b.*/SERIAL_INTERFACE=$(dmesg | grep "ttyUSB" | grep "attached" | cut -d ' ' -f13)/g" /home/ubuntu/webserver/properties.cfg

But it shows the error sed: -e expression #1, char 46: unterminated `s' command

Help me to figure out this.

Thank you in advance.

Replace:

sed -i "s/\b\SERIAL_INTERFACE=\b.*/SERIAL_INTERFACE=$(dmesg | grep "ttyUSB" | grep "attached" | cut -d ' ' -f13)/g" /home/ubuntu/webserver/properties.cfg

with:

sed -i "s/\bSERIAL_INTERFACE=\b.*/SERIAL_INTERFACE=$(dmesg | grep "ttyUSB" | grep "attached" | cut -d ' ' -f14| tr '\n' ' ' | tee save.tmp)/g" /home/ubuntu/webserver

The problem was that the pipeline produced multiple output lines. The solution is to add tr '\\n' ' ' to remove the newlines.

Four other comments:

  • The S in SERIAL_INTERFACE was escaped for no apparent reason. I removed that escape.

  • You reported success with the command cut -d ' ' -f14 but the pipeline command used cut -d ' ' -f13 .

  • As mentioned in the comments, you do have quotes within quotes but that is just fine: the inner quotes are inside of $(...) and thus do not interfere with the outer quotes.

  • The output of this command looks like:

     SERIAL_INTERFACE=ttyUSB0 ttyUSB1 

    Since you haven't said what your desired output is, I don't know if this is what you want or not.

Why the "unterminated s command" error?

Suppose we have a shell variable that contains a newline:

$ echo "$string"
a
b

When you substitute this variable into a sed command, sed sees the newline character as terminating a line which terminates the command. The result is an "unterminated s command":

$ echo hi | sed "s/hi/$string"
sed: -e expression #1, char 6: unterminated `s' command

By contrast, without the newline character, it works fine:

$ string="a b"
$ echo hi | sed "s/hi/$string/"
a b

In summary, when substituting shell variables into sed commands, one has to be very careful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM