[英]Compare text in Unix
我想在Unix中比較兩個文本。 我試過以下。 它沒用。 需要比較文件的第一行和最后一行。
firstline=`head -1 test.txt`
echo $firstline
lastline=`tail -1 test.txt`
echo $lastline
if [ $firstline == $lastline ]
then
echo "Found"
fi
當然,我錯過了一些東西。 請幫忙。
假設您正在使用“某種”bourne shell,您應該(a)引用變量並且(b)需要使用單個=
:
if [ "$firstline" = "$lastline" ]
then
echo "Found"
fi
更新在回復一些評論時,如果$firstline
為-z
,這也會有效。 即使在這種情況下,如果語句不被解釋為if [ -z ... ]
至少在ksh
(Korn Shell程序)或擊(我沒有與一個普通的Bourne shell的系統sh
可用)。
也許更簡單......
bash-3.2$ if [ "$(sed -n '1p' file)" = "$(sed -n '$p' file)" ]; then
echo 'First and last lines are the same'
else
echo 'First and last lines differ'
fi
更新以回答Jan的問題。
bash-3.2$ cat file
-z
-G
bash-3.2$ if [ "$(sed -n '1p' file)" = "$(sed -n '$p' file)" ]; then
> echo 'First and last lines are the same'
> else
> echo 'First and last lines differ'
> fi
First and last lines differ
我更喜歡sed
抓取文件的第一行和最后一行,因為相同的命令行適用於Linux,Mac OS和Solaris。 Linux和Solaris之間的head
和tail
命令行是不同的。
應該是if [ "$firstline" = "$lastline" ]
如果省略雙引號,則如果行包含白色字符,則無法使用。
至少,你必須引用變量擴展。 另外,如果字符串以-
開頭,則應添加前綴以避免出現問題。 正確的運算符是=
。 所以它應該是
if [ "x$firstline" = "x$lastline" ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.