简体   繁体   中英

How to use a shell variable inside sed when doing “d” command?

In my bash, I wish to delete lines from 1 to ${number}, like this:

number=10
sed '1,${number}d' myfile

It failed with syntax error. I also tried "\\${number}", '"$number"', neithers works


I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

sed表达式括在双引号内以插入变量number

sed "1,${number}d" file

Please use double quotes instead of single quotes while running sed this way. Read here for Difference between single and double quotes

I changed to double quote, it works under command line, but not inside bash script file

Assuming your bash script is:

sed "1,${number}d" myfile

you should export number variable in bash prompt so that it can be visible in bash script when it is run:

export number=10

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