如何从输入文件中读取路径

3

我有一个txt文件,其中包含指向xml文件的路径。现在我想从文本文件中读取路径,并打印每个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!"
2个回答

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!"

0
sudo_O提供了一个很好的答案。然而,有可能由于文本编辑器的偏好,你的制表符被转换为8个连续的空格。如果你也希望将它们视为制表符,请将"tabs"的定义替换为:
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 个连续的空格视为制表符的情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接