我們要檢查這個句子是聲明性的還是現在將其儲存在declarative.txt
文件中,然後將其餘句子放入others.txt
文件中,然後將行數放在declarative.txt
文件末尾。
如果一個句子以句號結尾,則該句子是「陳述性的」。
輸入檔($1)
this life is good.
neverthe less.
suppppppppppppppppperb.
the best coders.
everything is good?
are you okay dude?
ma man !!
到目前為止我的程式碼
#!/bin/sh
while read row
do
x=$row | grep "\.$"
y=$row | grep -v "\.$"
echo $x >> declarative.txt
echo $y >> others .txt
done < $1
cnt=`wc -l declarative.txt`
echo $cnt >> declarative.txt
答案1
要將輸入檔案中的行分為以點結尾的行和不以點結尾的行,假設每行只有一個句子,並將它們保存在兩個不同的輸出檔案中,您可以使用grep
兩次,如下所示:
grep '\.$' "$1" >declarative.txt
grep -v '\.$' "$1" >others.txt
不需要在 shell 循環中遍歷各行(事實上,它灰心喪志)。處理文字檔案的 Unix 工具已經內建了循環,因此grep
,例如,將依次將正規表示式應用於輸入資料的每一行並輸出匹配的資料。
您也可以只解析一次輸入文件,例如awk
:
awk '/\.$/ { print >"declarative.txt"; next }
{ print >"others.txt" }' "$1"
declarative.txt
如果當前行以點結尾,這將觸發將當前行列印到文件的區塊。將為所有其他線路觸發另一個區塊。
...或與sed
:
sed -n -e '/\.$/w declarative.txt' \
-e '//!w others.txt' "$1"
如果當前declarative.txt
行以點結尾,則將其寫入;others.txt
如果不是,則將其寫入。空//
表達式的意思是“重新使用最後一個正規表示式”,而!
意思是“做這如果表達式不匹配」。
答案2
這是不是辨識陳述句的有效方法。一方面,你的句子都沒有以大寫字母開頭,而且很多甚至根本不是句子。但是,如果您只想將輸入文件的行分成兩個文件,一個包含以句號結尾的行,另一個包含其餘行,您可以使用awk
:
awk '{/\.$/ ? f="fullStop" : f="others"; print > f}' file
如果您確實需要將其作為 shell 腳本來執行此操作,您可以簡單地使用:
#!/bin/sh
awk '{/\.$/ ? f="fullStop" : f="others"; print > f}' "$1"
如果它必須是一個 shell 循環 (這不是一個好主意), 你可以做:
#!/bin/bash
while IFS= read -r line; do
[[ $line =~ \.$ ]] &&
echo "$line" >> fullStop ||
echo "$line" >> others
done < "$1"
或者,如果您無法使用 bash 特定的功能:
#!/bin/sh
while IFS= read -r line; do
printf '%s\n' "$line" | grep -q '\.$' &&
echo "$line" >> fullStop ||
echo "$line" >> others
done < "$1"