简体   繁体   中英

Compare text in Unix

I am trying to compare two text in Unix. I tried the below. It didn't work. In need to compare the first and last lines of a file.

firstline=`head -1 test.txt`
echo $firstline
lastline=`tail -1 test.txt`
echo $lastline
if [ $firstline == $lastline ]
then
   echo "Found"
fi

Surely, am missing something. Please help.

Assuming you are using "some sort" of bourne shell, you should (a) quote the variables and (b) need to use a single = :

if [ "$firstline" = "$lastline" ]
then
   echo "Found"
fi

Update In response to some comments, this will also work if $firstline is -z . Even in this case the if statement is not interpreted as if [ -z ... ] , at least in the ksh (Korn Shell) or in Bash (I don't have a system with a plain bourne shell sh available).

Perhaps simpler...

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

Update to answer Jan's questions.

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

I prefer sed for grabbing the first and last lines of a file because the same command-line works on Linux, Mac OS and Solaris. The head and tail command-lines are different between Linux and Solaris.

Should be if [ "$firstline" = "$lastline" ]

If you omit double quotes it will not work if the line(s) contain white characters.

At the very least, you have to quote the variable expansions. Plus you should add prefix to avoid problems if the strings start with - . And the correct operator is = . So it should be

if [ "x$firstline" = "x$lastline" ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM