[英]I want my script to echo “$1” into a file literally
This is part of my script 这是我脚本的一部分
#!/bin/bash
echo "ls /SomeFolder | grep $1 | xargs cat | grep something | grep .txt | awk '{print $2}' | sed 's/;$//';" >> script2.sh
This echos everything nicely into my script except $1 and $2. 除了$ 1和$ 2,这一切都很好地呼应了我的脚本。 Instead of that it outputs the input of those variables but i want it to literally read "$1" and "$2".
取而代之的是,它输出这些变量的输入,但我希望它从字面上读取“ $ 1”和“ $ 2”。 Help?
救命?
Escape it: 逃脱它:
echo "ls /SomeFolder | grep \$1 | xargs cat | grep something | grep .txt | awk '{print \$2}' | sed 's/;\$//';" >> script2.sh
Quote it: 引用它:
echo "ls /SomeFolder | grep "'$'"1 | xargs cat | grep something | grep .txt | awk '{print "'$'"2}' | sed 's/;"'$'"//';" >> script2.sh
or like this: 或像这样:
echo 'ls /SomeFolder | grep $1 | xargs cat | grep something | grep .txt | awk '\''{print $2}'\'' | sed '\''s/;$//'\'';' >> script2.sh
Use quoted here document : 使用此处引用的文档 :
cat << 'EOF' >> script2.sh
ls /SomeFolder | grep $1 | xargs cat | grep something | grep .txt | awk '{print $2}' | sed 's/;$//';
EOF
Basically you want to prevent expansion, ie. 基本上,您想防止扩展,即。 take the string literaly.
取字面意义上的字符串。 You may want to read bashfaq quotes
您可能需要阅读bashfaq报价
First, you'd never write this (see https://mywiki.wooledge.org/ParsingLs , http://porkmail.org/era/unix/award.html and you don't need greps+seds+pipes when you're using awk): 首先,你永远也不会写这篇文章(见https://mywiki.wooledge.org/ParsingLs , http://porkmail.org/era/unix/award.html你不需要里grep + SEDS +管道,当你正在使用awk):
ls /SomeFolder | grep $1 | xargs cat | grep something | grep .txt | awk '{print $2}' | sed 's/;$//'`
you'd write this instead: 您可以这样写:
find /SomeFolder -mindepth 1 -maxdepth 1 -type f -name "*$1*" -exec \
awk '/something/ && /.txt/{sub(/;$/,"",$2); print $2}' {} +
or if you prefer using print | xargs
或者如果您喜欢使用
print | xargs
print | xargs
instead of -exec
: print | xargs
而不是-exec
:
find /SomeFolder -mindepth 1 -maxdepth 1 -type f -name "*$1*" -print0 |
xargs -0 awk '/something/ && /.txt/{sub(/;$/,"",$2); print $2}'
and now to append that script to a file would be: 现在将该脚本附加到文件将是:
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
Btw, if you want the .
顺便说一句,如果你想要的
.
in .txt
to be treated literally instead of as a regexp metachar meaning "any character" then you should be using \\.txt
instead of .txt
. 在
.txt
中将其按字面意义处理,而不是被视为表示“任何字符”的正则表达式元字符,那么您应该使用\\.txt
而不是.txt
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.