gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:09:32 37 4
gpt4 key购买 nike

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

我的代码如下:

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

我收到以下错误:

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

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

谢谢

最佳答案

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

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

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

关于bash - 将文件名变量传递给 sed 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32135553/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com