【问题标题】:Read line by line from a text file and print how I want in shell scripting从文本文件中逐行读取并在 shell 脚本中打印我想要的方式
【发布时间】:2018-11-15 08:57:13
【问题描述】:

我想从文本文件中逐行读取下面的文件,并在 shell 脚本中打印我想要的方式

Text file content:   
zero#123456  
one#123  
two#12345678 

我想把它打印成:

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"    

【问题讨论】:

  • 如果你有three#123789?结果应该是three@1-9 还是类似three@1-3,7-9 的东西?

标签: shell


【解决方案1】:

创建如下脚本: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"

像这样运行它:

mayankp@mayank:~/$ sh my_print.sh 
mayankp@mayank:~/$ cat output.txt 
zero@1-6
one@1-3
two@1-8

让我知道这会有所帮助。

【讨论】:

  • 它工作正常,但它只打印一行而不打印第二行。输出:$ cat output.txt zero@1-5
  • 我正在将输出写入文件output.txt。如果您只想打印它,请查看我更新的答案。
  • 谢谢马扬克。我试过了,但我再次把它当作一条线。即使我尝试在 output.txt 中打印它
  • 我粘贴了经过测试的解决方案。它在我的机器上运行良好。您是否在粘贴在帖子中的同一文件上运行它?请检查一下,您可能会遗漏一些非常简单的东西。
  • 谢谢马扬克。你能解释一下步骤吗?会有帮助的
【解决方案2】:

这不是 shell 脚本(首先错过了,抱歉),而是使用 perl 与前瞻和后瞻组合的数字:

$ perl -pe 's/(?<=[0-9]).*(?=[0-9])/-/' file
Text file content:   
zero#1-6  
one#1-3  
two#1-8 

解释了一些:

  • s//-/ 替换为 -
  • (?&lt;=[0-9]) 正向向后看,如果前面有数字
  • (?=[0-9]) 正向前瞻,如果后跟一个数字

【讨论】:

    【解决方案3】:

    使用 sed:

    sed -r 's/^(.+)#([0-9])[0-9]*([0-9])\s*$/\1@\2-\3/' readFile.txt
    
    • -r:使用扩展正则表达式(只是为了写一些东西而不用反斜杠转义)
    • s/expr1/expr2/s替代expr1 by expr2
    • epxr1 由正则表达式描述,相关匹配模式被 3 个捕获组(括号内)捕获。
    • epxr2 检索捕获的字符串(\1\2\3)并将它们插入到格式化输出(您想要的输出)中。

    Regular-Expressions.info 从他们开始似乎很有趣。你也可以用Regx101.com检查你自己的正则表达式。

    更新:你也可以用 awk 做到这一点:

    awk -F'#' '{ \
                 gsub(/\s*/,"", $2) ; \
                 print $1 "@" substr($2, 1, 1) "-" substr($2, length($2), 1) \
               }' < test.txt
    

    我添加了一个gsub() 调用,因为您的文件似乎有尾随空白字符。

    【讨论】:

      猜你喜欢
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-24
      相关资源
      最近更新 更多