运行 shell 脚本,直到文件中只剩下一行

运行 shell 脚本,直到文件中只剩下一行
#!/bin/sh
echo "file to split?"
read file
f=0
until ! [ -s $file ];
do
        grep -n "<text" $file > titles.txt
        lines=$(cat titles.txt| sed -n 2'p' | sed -r 's/^([0-9]*).*/\1/g')
        f=$((f+1))
        substrac="$(($lines-1))"
        head -$substrac $file > $f
        sed -i '1,'$substrac'd' $file
        echo "file \"$f\" generated"
done

该脚本运行直到为$file空,但我需要它运行直到文件“titles.txt”中剩下 1 行或<text$file 中出现一次“”。

我努力了:

while :
do
        count=$(grep "<text" $file | wc -l)
if [ $count > 1 ]
then

和:

while :
count=$(cat titles.txt | wc -l);
do
until [ $count -eq 1 ]; do

但我无法让脚本在那一点停止,我确信我做错了什么,但我找不到什么......

答案1

如果该文件是格式良好的 XML 文件,并且您想要将<text>节点提取到单独的文件中,则可以使用 XMLStarlet 执行以下操作:

#!/bin/sh

infile="$1"

xmlstarlet sel -t -v '//text/@id' -nl "$infile" |
while read id; do
    xmlstarlet sel -t --var id="'$id'" -v '//text[@id = $id]' "$infile" >"$id.txt"
done

在命令行中给出如下文件的路径名,

<?xml version="1.0"?>
<root>
  <text id="cade2296-1">
The first text, called "cade2296-1".
</text>
  <text id="cafr3062-1">
The second text, called "cafr3062-1".
</text>
</root>

...这将在当前目录中创建两个文件cade2296-1.txt和,其中包含原始文件中cafr3062-1.txt两个标签的内容。<text>

文件名取自标签id的属性<text>id首先从 XML 中提取这些值,然后在循环中使用它来提取相关的标记值。

在循环内的 XMLStarlet 调用中更改-v为将为您提供-c复制XML 标签的<text>内容,而不仅仅是标签中的数据。

答案2

是的,感谢@George Vasiliou,我可以让它工作,现在脚本是这样的:

#!/bin/sh
echo "file to split?"
read file

# This variable is to name resulting files
f=0

while :
do
    # Count how many occurrences of "<text" are in the file to split
    count=$(grep "<text" "$file" | wc -l)
if [ "$count" -gt 1 ]
then

    # Send the occurrences of "<text" with their line number to the titles.txt file
    grep -n "<text" "$file" > titles.txt

    # From the second line of titles get the line number
    lines=$(cat titles.txt| sed -n 2'p' | sed -r 's/^([0-9]*).*/\1/g')

    # Every time the script is run the resulting file gets the next number as name      
    f=$((f+1))

    # From the line number obtained at the second line substract 1
    substrac="$(($lines-1))"

    # Create a new file taking the amount of lines indicated by the substraction from the splitting file
    head -"$substrac" "$file" > "$f"

    # Delete the lines corresponding to the newly created file from the splitting file to start the process over
    sed -i '1,'"$substrac"'d' "$file"
    echo "file \"$f\" generated"
else
    echo "process finished!"
    exit 1;
fi
done

解释:我有一个巨大的文本文件,格式如下:

  <text id="cade2296-1">
  many
  undetermined
  lines
  ...
 </text>

 The same schema repeteated undetermined times

  <text id="cafr3062-1">
  many
  undetermined
  lines
  ...
 </text>

我需要的是不同文件中的每个模式。

相关内容