繁体   English   中英

我希望我的脚本从字面上回显“ $ 1”到文件中

[英]I want my script to echo “$1” into a file literally

这是我脚本的一部分

#!/bin/bash

echo "ls /SomeFolder | grep $1 | xargs cat | grep something | grep  .txt | awk '{print $2}' | sed 's/;$//';" >> script2.sh

除了$ 1和$ 2,这一切都很好地呼应了我的脚本。 取而代之的是,它输出这些变量的输入,但我希望它从字面上读取“ $ 1”和“ $ 2”。 救命?

逃脱它:

echo "ls /SomeFolder | grep \$1 | xargs cat | grep something | grep  .txt | awk '{print \$2}' | sed 's/;\$//';" >> script2.sh

引用它:

echo "ls /SomeFolder | grep "'$'"1 | xargs cat | grep something | grep  .txt | awk '{print "'$'"2}' | sed 's/;"'$'"//';" >> script2.sh

或像这样:

echo 'ls /SomeFolder | grep $1 | xargs cat | grep something | grep  .txt | awk '\''{print $2}'\'' | sed '\''s/;$//'\'';' >> script2.sh

使用此处引用的文档

cat << 'EOF' >> script2.sh
ls /SomeFolder | grep $1 | xargs cat | grep something | grep  .txt | awk '{print $2}' | sed 's/;$//';
EOF

基本上,您想防止扩展,即。 取字面意义上的字符串。 您可能需要阅读bashfaq报价

首先,你永远也不会写这篇文章(见https://mywiki.wooledge.org/ParsingLshttp://porkmail.org/era/unix/award.html你不需要里grep + SEDS +管道,当你正在使用awk):

ls /SomeFolder | grep $1 | xargs cat | grep something | grep  .txt | awk '{print $2}' | sed 's/;$//'`

您可以这样写:

find /SomeFolder -mindepth 1 -maxdepth 1 -type f -name "*$1*" -exec \
    awk '/something/ && /.txt/{sub(/;$/,"",$2); print $2}' {} +

或者如果您喜欢使用print | xargs print | xargs而不是-exec

find /SomeFolder -mindepth 1 -maxdepth 1 -type f -name "*$1*" -print0 |
    xargs -0 awk '/something/ && /.txt/{sub(/;$/,"",$2); print $2}'

现在将该脚本附加到文件将是:

cat <<'EOF' >> script2.sh
find /SomeFolder -mindepth 1 -maxdepth 1 -type f -name "*$1*" -print0 |
    xargs -0 awk '/something/ && /.txt/{sub(/;$/,"",$2); print $2}'
EOF

顺便说一句,如果你想要的. .txt中将其按字面意义处理,而不是被视为表示“任何字符”的正则表达式元字符,那么您应该使用\\.txt而不是.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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