Как я могу отобразить первые n разных строк в двух файлах из оболочки?

Если вы смотрите на переменную для определения потока, вы хотите использовать оператор case.

case "$var" in
   val1)
      do_something
      ;;
   val2)
      do_something_else
      ;;
esac

Если вы хотите получить пользовательский ввод в интерактивном режиме, вы также можете использовать оператор select.

select action in proceed ponder perspire quit; do
    case "$action" in
        proceed)
           go_on_then
           ;;
        ponder)
           have_a_think
           ;;
        perspire)
           exude_salty_secretions
           ;;
        quit)
           break
           ;;
    esac
done
0
19.03.2020, 09:01
3 ответа

Предполагая, что ваши файлы не содержат символ TAB (, если он есть, выберите другой однозначный разделитель ), который вы могли бы сделать

$ paste file1 file2 | awk -F'\t' '$2 != $1 {print $2; n++} n==5 {exit}'
This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT
1
28.04.2021, 23:20

Это мое предложение:

diff -u file1 file2 --unchanged-line-format= --old-line-format= --new-line-format=%L | head -n 5

This line is not the same
This is still not the same
Neither is this
Nor this
DIFFERENT
3
28.04.2021, 23:20

Использование примитивов bash, использование фиксированных файловых дескрипторов для простоты. (Не проверено)

# open the two files on fd8 and fd9, should have some error checking
exec 8<file1 9<file2
# start the loop
for(c=0;c<6;)
do
    # read a line from first file, don't worry about EOF 
    IFS="" read -r -u 8 l1
    # read a line from second file, exit the loop if EOF
    read -r -u 9 l2 || break
    # loop if the 2 lines are the same
    [ "$l1" -eq "$l2" ] && continue
    # ok, a different line. Output from file2, bump count and loop
    let c++
    printf '%s\n' "$l2"
done
# If we get here we either have hit EOF on file2 or have printed our 6 lines
# Either way just tidy up
# close the file descriptiors
exec 8<&- 9<&-
0
28.04.2021, 23:20

Теги

Похожие вопросы