combine two sed commands [duplicate]

2019-07-16 14:12发布

This question already has an answer here:

How can I combine the following two sed commands.

One loops all files in a directory and removes the first line from them. The other removes any double quotes " from the start of file lines.

Remove first line of each file

for each in `/bin/ls -1`;do sed -i 1d $each;done

Beginning of line

for each in `/bin/ls -1`;do sed -i 's/^"//g' $each;done

4条回答
▲ chillily
2楼-- · 2019-07-16 14:56

You can do:

for each in *; do sed -i.bak 's/^"//g; 1d' "$each"; done
查看更多
疯言疯语
3楼-- · 2019-07-16 15:06

You can do it with a single commmand in this way:

sed -i.bak --separate '1d ; s/^"//' *

Explanation

With --separate you're telling sed to treat the files separately, the default is to process them as a long single file but you are using adresses (1 in the first command) so the default doesn't work.

'1d ; s/^"//' just combines the two commands (separated by ;).

查看更多
Emotional °昔
4楼-- · 2019-07-16 15:09

You can put them into the same invocation of sed like this:

for f in *; do sed -i '1d;s/^"//' "$f"; done

As well as combining the two sed commands, I have also used a glob * rather than attempting to parse ls, which is never a good idea.

Also, your substitution needn't be global, as it can by definition only apply to each line once, so I removed the g modifier as well.

查看更多
一纸荒年 Trace。
5楼-- · 2019-07-16 15:11

You can use -e to perform different sed commands in the same line: sed -e 'command_1' -e 'command_2' ... -e 'command_n'. You can also use sed 'command_1; command_2; ...; command_n.

Let's use the first option and loop through the files:

for file in *
do
    sed -i.bak -e '1d' -e 's/^"//' "$file"
done

Note also that I use for file in *, so that * expands to the files in the current directory. This is better than parsing the output of ls (Why you shouldn't parse the output of ls(1) is a good read).

Finally, it is a good practise to create a backup file when using -i, as anubhava suggests. This way, you are always in the safe side :)

查看更多
登录 后发表回答