[英]How to replace a string into date format MM/DD/YYY argument from an user input by using awk script within bash script?
Couldn't figure how to replace a string from text file into date format MM/DD/YYYY from user input as an argument.无法弄清楚如何将文本文件中的字符串替换为用户输入的日期格式 MM/DD/YYYY 作为参数。 For example:例如:
$ ./test.bash text.txt 09/16/2020
The date was 09/16/2020
text.txt文本.txt
The date was [[date_arg]]
$cat test.bash $猫测试.bash
#!/bin/bash
text=$filename.txt
date=$(date +$m/$d/$Y)
if [[ $# -eq 1 ]]; then
text=$1
elif [[ $# -eq 2 ]]; then
text=$1
date=$2
awk -f f.awk $text $date
fi
I was using a sed code within awk script to see if it works with it, but it didn't works out.我在 awk 脚本中使用了 sed 代码来查看它是否适用,但没有成功。
f.awk f.awk
BEGIN {
RS=""
}
NR==FNR {
t=$0
next
}
{
sub(/\[\[date_arg\]\]/,$(date+ $m/$d/$Y),t)
print t
}
Going by OP's attempt here, could you please try following.按照 OP 的尝试,请您尝试以下操作。 cat script.bash
only there to show script's content actual script starts from #!
cat script.bash
只是为了显示脚本的内容实际脚本从#!
line.线。
cat script.bash
#!/bin/bash
if [[ $# -eq 2 ]]
then
file=$1
myDate=$2
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"
In case you want to save output into provided file name itself(inplace editing) then change above awk
command to awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" > temp && mv temp "$file"
, better to test above first and then look for inplace editing.如果您想将 output 保存到提供的文件名本身(就地编辑),然后将上面的awk
命令更改为awk -v date="$myDate" '{sub(/\[\[date_arg\]\]/,date)} 1' "$file" > temp && mv temp "$file"
,最好先在上面测试,然后寻找就地编辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.