如何通过在 bash 脚本中使用 awk 脚本将用户输入的字符串替换为日期格式 MM/DD/YYY 参数?
How to replace a string into date format MM/DD/YYY argument from an user input by using awk script within bash script?
无法确定如何将文本文件中的字符串替换为用户输入的日期格式 MM/DD/YYYY 作为参数。
例如:
$ ./test.bash text.txt 09/16/2020
The date was 09/16/2020
text.txt
The date was [[date_arg]]
$猫test.bash
#!/bin/bash
text=$filename.txt
date=$(date +$m/$d/$Y)
if [[ $# -eq 1 ]]; then
text=
elif [[ $# -eq 2 ]]; then
text=
date=
awk -f f.awk $text $date
fi
我在 awk 脚本中使用了 sed 代码来查看它是否适用于它,但没有成功。
f.awk
BEGIN {
RS=""
}
NR==FNR {
t=[=15=]
next
}
{
sub(/\[\[date_arg\]\]/,$(date+ $m/$d/$Y),t)
print t
}
按照OP的尝试,请您尝试以下。 cat script.bash
仅用于显示脚本的内容实际脚本从 #!
行开始。
cat script.bash
#!/bin/bash
if [[ $# -eq 2 ]]
then
file=
myDate=
elif [[ $# -lt 2 ]]
then
echo "Please pass 2 arguments in script, where 1st should be Input_file name and 2nd should be date in mm-dd-yyyy format. Exiting from script now.."
exit 1;
fi
awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file"
如果您想将输出保存到提供的文件名本身(就地编辑),则将上面的 awk
命令更改为 awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" > temp && mv temp "$file"
,最好先测试上面的命令,然后再寻找就地编辑。
无法确定如何将文本文件中的字符串替换为用户输入的日期格式 MM/DD/YYYY 作为参数。 例如:
$ ./test.bash text.txt 09/16/2020
The date was 09/16/2020
text.txt
The date was [[date_arg]]
$猫test.bash
#!/bin/bash
text=$filename.txt
date=$(date +$m/$d/$Y)
if [[ $# -eq 1 ]]; then
text=
elif [[ $# -eq 2 ]]; then
text=
date=
awk -f f.awk $text $date
fi
我在 awk 脚本中使用了 sed 代码来查看它是否适用于它,但没有成功。
f.awk
BEGIN {
RS=""
}
NR==FNR {
t=[=15=]
next
}
{
sub(/\[\[date_arg\]\]/,$(date+ $m/$d/$Y),t)
print t
}
按照OP的尝试,请您尝试以下。 cat script.bash
仅用于显示脚本的内容实际脚本从 #!
行开始。
cat script.bash
#!/bin/bash
if [[ $# -eq 2 ]]
then
file=
myDate=
elif [[ $# -lt 2 ]]
then
echo "Please pass 2 arguments in script, where 1st should be Input_file name and 2nd should be date in mm-dd-yyyy format. Exiting from script now.."
exit 1;
fi
awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file"
如果您想将输出保存到提供的文件名本身(就地编辑),则将上面的 awk
命令更改为 awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" > temp && mv temp "$file"
,最好先测试上面的命令,然后再寻找就地编辑。