从文本文件中逐行读取,并在shell脚本中打印所需内容
我想从文本文件中逐行阅读下面的文件,并在shell脚本中打印我想要的方式 我想将此打印为:从文本文件中逐行读取,并在shell脚本中打印所需内容,shell,Shell,我想从文本文件中逐行阅读下面的文件,并在shell脚本中打印我想要的方式 我想将此打印为: zero@1-6 one@1-3 two@1-8 我尝试了以下方法: file="readFile.txt" while IFS= read -r line do echo "$line" done <printf '%s\n' "$file" file=“readFile.txt” 而IFS=读取-r行 不回显“$line” 完成创建如下脚本
zero@1-6
one@1-3
two@1-8
我尝试了以下方法:
file="readFile.txt"
while IFS= read -r line
do echo "$line"
done <printf '%s\n' "$file"
file=“readFile.txt”
而IFS=读取-r行
不回显“$line”
完成创建如下脚本:my_print.sh
file="readFile.txt"
while IFS= read -r line
do
one=$(echo $line| awk -F'#' '{print $1}') ## This splits the line based on '#' and picks the 1st value. So, we get zero from 'zero#123456 '
len=$(echo $line| awk -F'#' '{print $2}'|wc -c) ## This takes the 2nd value which is 123456 and counts the number of characters
two=$(echo $line| awk -F'#' '{print $2}'| cut -c 1) ## This picks the 1st character from '123456' which is 1
three=$(echo $line| awk -F'#' '{print $2}'| cut -c $((len-1))) ## This picks the last character from '123456' which is 6
echo $one@$two-$three ## This is basically printing the output in the format you wanted 'zero@1-6'
done <"$file"
让我知道这对我有帮助。使用sed:
sed -r 's/^(.+)#([0-9])[0-9]*([0-9])\s*$/\1@\2-\3/' readFile.txt
-r
:使用扩展正则表达式(只编写一些东西而不使用反斜杠转义)
s/expr1/expr2/
:s用expr2
替代expr1
epxr1
由正则表达式描述,相关匹配模式由3个捕获组(括号内的组)捕获李>
epxr2
检索捕获的字符串(\1
,\2
,\3
)并将其插入格式化输出(您想要的输出)
从他们开始似乎很有趣。您还可以使用检查自己的regexp
更新:您也可以使用awk:
awk -F'#' '{ \
gsub(/\s*/,"", $2) ; \
print $1 "@" substr($2, 1, 1) "-" substr($2, length($2), 1) \
}' < test.txt
awk-F'#''''{\
gsub(/\s*/,“”,$2)\
打印$1“@”substr($2,1,1)”-“substr($2,length($2),1)\
}“
我添加了一个gsub()
调用,因为您的文件似乎有尾随的空白字符。这不是shell脚本(首先错过了,很抱歉),而是使用perl并结合使用前向和后向查找来获得一个数字:
$ perl -pe 's/(?<=[0-9]).*(?=[0-9])/-/' file
Text file content:
zero#1-6
one#1-3
two#1-8
$perl-pe的/(?工作正常,但只打印一行,不打印第二行。输出:$cat Output.txtzero@1-5我正在将输出写入一个文件output.txt
。如果您只想打印它,请检查我的更新答案。谢谢mayank。我尝试了,但再次得到的结果仅为一行。甚至我也尝试在output.tx中打印它我粘贴了测试过的解决方案。它在我的机器上运行得很好。你是否在粘贴到帖子的同一个文件上运行它?请检查,一定有一些非常简单的东西你可能遗漏了。谢谢mayank。请你解释一下步骤。这会很有帮助。如果你有three#123789
,结果应该是three吗@1-9
或类似的three@1-3,7-9
?
awk -F'#' '{ \
gsub(/\s*/,"", $2) ; \
print $1 "@" substr($2, 1, 1) "-" substr($2, length($2), 1) \
}' < test.txt
$ perl -pe 's/(?<=[0-9]).*(?=[0-9])/-/' file
Text file content:
zero#1-6
one#1-3
two#1-8