【问题标题】:How to read path from input file如何从输入文件中读取路径
【发布时间】:2013-03-21 11:09:03
【问题描述】:

我有一个包含 xml 文件路径的 txt 文件。现在我想从文本文件中读取路径并打印每个 xml 文件中存在的选项卡数。如何执行此操作?

这就是我所做的

带有路径的txt文件

/home/user/Desktop/softwares/firefox/searchplugins/bing.xml
/home/user/Desktop/softwares/firefox/searchplugins/eBay.xml
/home/user/Desktop/softwares/firefox/searchplugins/answers.xml
/home/user/Desktop/softwares/firefox/searchplugins/wikipedia.xml
/home/user/Desktop/softwares/firefox/blocklist.xml

计算每个文件中标签的代码

代码:

#!/bin/sh
#
FILEPATH=/home/user/Desktop/softwares/firefox/*.xml
for file in $FILEPATH; do
    tabs=$(tr -cd '\t' < $file  | wc -c);
    echo "$tabs tabs in file $file" >> /home/user/Desktop/output.txt
done
echo "Done!"

【问题讨论】:

    标签: linux bash shell sh


    【解决方案1】:

    /home/user/Desktop/files.txt 包含 xml 文件列表:

    #!/bin/bash
    
    while IFS= read file
    do 
        if [ -f "$file" ]; then
           tabs=$(tr -cd '\t' < "$file"  | wc -c);
           echo "$tabs tabs in file $file" >> "/home/user/Desktop/output.txt"
        fi
    done < "/home/user/Desktop/files.txt"
    echo "Done!"
    

    【讨论】:

      【解决方案2】:

      sudo_O 提供了一个很好的答案。但是,有可能不知何故,主要是由于文本编辑器的偏好,您的选项卡被转换为 8 个连续空格。如果您也希望将它们视为选项卡,请将“选项卡”定义替换为:

      tabs=$(cat test.xml | sed -e 's/ \{8\}/\t/g' | tr -cd '\t' | wc -c)
      

      完整代码:

      #!/bin/sh
      
      # original file names might contain spaces
      # FILEPATH=/home/user/Desktop/softwares/firefox/*.xml
      # a better option would be
      FIREFOX_DIR="/home/user/Desktop/softwares/firefox/"
      
      while read file
      do
          if [[ -f "$file" ]] 
          then
              tabs=$(cat test.xml | sed -e 's/ \{8\}/\t/g' | tr -cd '\t' | wc -c)
              echo "$tabs tabs in file $file" >> /home/user/Desktop/output.txt
          fi
      done < $FIREFOX_DIR/*.xml
      
      echo "Done!"
      

      但这仅适用于您希望将 8 个连续空格计为制表符的情况。

      【讨论】:

        猜你喜欢
        • 2017-07-27
        • 1970-01-01
        • 2013-12-16
        • 2018-01-07
        • 2022-06-11
        • 2012-09-22
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        相关资源
        最近更新 更多