bash 将文件名变量传递给 sed 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32135553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:28:24  来源:igfitidea点击:

Pass filename variable into sed command

bashshellunixsed

提问by Ben

I am attempting to write a small shell script that firstly defines a file name using date and then runs two sed commands which strip out certain characters.

我正在尝试编写一个小的 shell 脚本,它首先使用 date 定义一个文件名,然后运行两个 sed 命令来去除某些字符。

My code is as follows:

我的代码如下:

filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)//g' '&filename'
sed -i 's/\"//g' '&filename'

I am getting the following error:

我收到以下错误:

sed: can't read &filename: No such file or directory
sed: can't read &filename: No such file or directory

Question is, how can I pass this filename variable into the sed command?

问题是,如何将此文件名变量传递给 sed 命令?

Thanks

谢谢

回答by Eduardo Yá?ez Parareda

When doing shell scripting, for referencing variables the & (ampersand) is not used, but the $ (dollar sign):

在编写 shell 脚本时,不使用 &(与号)来引用变量,而是使用 $(美元符号):

filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)//g' "$filename"
sed -i 's/\"//g' "$filename"

Also when referencing variables, double quotes must be used, if not, bash won't interpret the meaning of the $ sign.

同样在引用变量时,必须使用双引号,否则,bash 不会解释 $ 符号的含义。

回答by davidcondrey

You want to use double-quotes when passing a variable to sed. If you use single quotes, the variable will be read literally.

在将变量传递给sed. 如果使用单引号,变量将按字面意思读取。

To use a shell variable in a command, preface it with a dollar sign ($). This tells the command interpreter that you want the variable's value, not its name, to be used.

要在命令中使用 shell 变量,请在它前面加上美元符号 ($)。这告诉命令解释器您希望使用变量的值,而不是它的名称。

filename=/var/local/file1/tsv_`date '+%d%m%y'`.txt
sed -i 's/\("[^,]*\)[,]\([^"]*"\)//g' "$filename"
sed -i 's/\"//g' "$filename"