Нумерация абзацев с командой 'кошки'

Я в настоящее время пытаюсь найти способ использовать команду кошки для показывания текстового файла автоматически пронумерованными абзацами для проекта, который я делаю, но я не смог найти единственную команду.

Пример:

Frederick II (German: Friedrich; 24 January 1712 – 17 August 1786) was King of Prussia from 1740 until 1786.[1] His most significant accomplishments during his reign included his military victories, his reorganization of Prussian armies, his patronage of the Arts and the Enlightenment in Prussia, and his final success against great odds in the Seven Years' War. 

Frederick was the last titled King in Prussia and declared himself King of Prussia after achieving full sovereignty for all historical Prussian lands. Prussia had greatly increased its territories and became a leading military power in Europe under his rule. He became known as Frederick the Great (Friedrich der Große) and was affectionately nicknamed Der Alte Fritz ("Old Fritz") by the Prussian people.

Затем, после того как команда была введена:

1. Frederick II (German: Friedrich; 24 January 1712 – 17 August 1786) was King of Prussia from 1740 until 1786.[1] His most significant accomplishments during his reign included his military victories, his reorganization of Prussian armies, his patronage of the Arts and the Enlightenment in Prussia, and his final success against great odds in the Seven Years' War. 

2.Frederick was the last titled King in Prussia and declared himself King of Prussia after achieving full sovereignty for all historical Prussian lands. Prussia had greatly increased its territories and became a leading military power in Europe under his rule. He became known as Frederick the Great (Friedrich der Große) and was affectionately nicknamed Der Alte Fritz ("Old Fritz") by the Prussian people.

Это - что-то, что я честно думал, что найду легко, но я не смог найти единственный веб-сайт с ответом о том, как сделать это. (Следует иметь в виду, что это должно быть изменение cat команда.)

5
задан 8 September 2016 в 12:11

5 ответов

Если абзац является на самом деле строкой как Ваш пример, и необходимо использовать только cat, затем, конечно, Вы хотите -b (число непустые строки)?

cat -b file

похож:

     1  Frederick II (German: Friedrich; 24 January 1712 – 17 August 1786) was King of Prussia from 1740 until 1786.[1] His most significant accomplishments during his reign included his military victories, his reorganization of Prussian armies, his patronage of the Arts and the Enlightenment in Prussia, and his final success against great odds in the Seven Years' War. 

     2  Frederick was the last titled King in Prussia and declared himself King of Prussia after achieving full sovereignty for all historical Prussian lands. Prussia had greatly increased its territories and became a leading military power in Europe under his rule. He became known as Frederick the Great (Friedrich der Große) and was affectionately nicknamed Der Alte Fritz ("Old Fritz") by the Prussian people.

Сохранить это в файле вместо того, чтобы печатать в терминале:

cat -b file > file2

В случае, если Вам действительно нужны они, Вы могли добавить точки после своих чисел, хотя не, afaik, не обращаясь к использованию другой команды для помощи cat, как sed, который здесь заменяет пробел и числа в строках, которые запускаются с них (так как cat -b отступы) с тем же шаблоном плюс a . сделать 1. 2. и т.д. (это было предложено @terdon так ослепительно быстро, у меня не было времени, чтобы сделать его самого и взять кредит),

cat -b file | sed -r 's/^\s+[0-9]+/&./' > file2

13
ответ дан 23 November 2019 в 08:38

В Вашем примере каждый абзац является на самом деле просто одной строкой. Единственным путем это было бы сформировано в абзац, будет переносом текста в том, какой бы ни приложение использовалось для отображения его.

можно пронумеровать все непустые строки в файле, с помощью cat с:

cat -b file

, Если Вы хотите отправить это в другой файл, используйте перенаправление:

cat -b file > newfile

Эти man команда действительно полезна для приобретения знаний об использовании для других команд, например man cat дает:

NAME

       cat - concatenate files and print on the standard output

SYNOPSIS

       cat [OPTION]... [FILE]...

DESCRIPTION

       Concatenate FILE(s), or standard input, to standard output.

       -A, --show-all
              equivalent to -vET

       -b, --number-nonblank
              number nonempty output lines, overrides -n

       -e     equivalent to -vE

       -E, --show-ends
              display $ at end of each line

       -n, --number
              number all output lines

       -s, --squeeze-blank
              suppress repeated empty output lines

       -t     equivalent to -vT

       -T, --show-tabs
              display TAB characters as ^I

       -u     (ignored)

       -v, --show-nonprinting
              use ^ and M- notation, except for LFD and TAB

       --help display this help and exit

       --version
              output version information and exit

       With no FILE, or when FILE is -, read standard input.

EXAMPLES

       cat f - g
              Output f's contents, then standard input, then g's contents.

       cat    Copy standard input to standard output.

AUTHOR

       Written by Torbjorn Granlund and Richard M. Stallman.

REPORTING BUGS

       Report cat bugs to bug-coreutils@gnu.org
       GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
       General help using GNU software: <http://www.gnu.org/gethelp/>
       Report cat translation bugs to <http://translationproject.org/team/>

COPYRIGHT

       Copyright  ©  2013  Free Software Foundation, Inc.  License GPLv3+: GNU
       GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
       This is free software: you are free  to  change  and  redistribute  it.
       There is NO WARRANTY, to the extent permitted by law.

SEE ALSO

       tac(1)

       The  full  documentation for cat is maintained as a Texinfo manual.  If
       the info and cat programs are properly  installed  at  your  site,  the
       command

              info coreutils 'cat invocation'

       should give you access to the complete manual.
7
ответ дан 23 November 2019 в 08:38

Я не знаю ни о какой команде "абзаца". cat -b то, что Вы хотите использовать.

Принятие этого для определенной управляемой задачи оценки в этом году ;) Беспорядок между строками и нумерацией абзацев, вероятно, происходит от того, которые, если Вы делаете текстовый файл с помощью pico/nano Вас, заставили его быть похожим на абзац путем нажатия Enter при записи содержания, поэтому каждый из "абзацев" является только одной строкой.

Попытка, делающая файл в тестовом редакторе в настольной среде, которая имеет переход на новую строку. Вы будете видеть cat -b выходные взгляды, как Вы ожидали. Абзац в редакторе командной строки является просто очень длинной одной строкой текста, который не делает слова, переносятся.

0
ответ дан 23 November 2019 в 08:38

Если "абзацами" Вы имеете в виду блоки строк, разделенных пустыми строками, Вы могли бы добавить нумерацию с простой командой awk:

awk -v RS= '{print ++i, $0}' file

Для сохранения пустых строк в выводе можно установить переменную ORS на \n\n как это:

awk -v RS= -vORS='\n\n' '{print ++i, $0}' file

Если Вы хотите сохранить вывод в новый файл, можно использовать перенаправление как это:

awk -v RS= '{print ++i, $0}' file > newfile
6
ответ дан 23 November 2019 в 08:38

"Абзацы" еще не являются абзацами, просто длинные линии (как другие отметили),

Мы должны пронумеровать строки и затем превратить их в абзацы, можно использовать сгиб для этого.

cat -b file | fold -sw 80

Это нумерует непустые строки, каналы это в сгиб, который сохраняет ширину в 80 символах (или столбцы) и повреждает строку на пробелах.

Frederick II (German: Friedrich; 24 January 1712 – 17 August 1786) was King of Prussia from 1740 until 1786.[1] His most significant accomplishments during his reign included his military victories, his reorganization of Prussian armies, his patronage of the Arts and the Enlightenment in Prussia, and his final success against great odds in the Seven Years' War.

Frederick was the last titled King in Prussia and declared himself King of Prussia after achieving full sovereignty for all historical Prussian lands. Prussia had greatly increased its territories and became a leading military power in Europe under his rule. He became known as Frederick the Great (Friedrich der Große) and was affectionately nicknamed Der Alte Fritz ("Old Fritz") by the Prussian people.

     1  Frederick II (German: Friedrich; 24 January 1712 – 17 August 1786)
was King of Prussia from 1740 until 1786.[1] His most significant
accomplishments during his reign included his military victories, his
reorganization of Prussian armies, his patronage of the Arts and the
Enlightenment in Prussia, and his final success against great odds in the Seven
Years' War.

     2  Frederick was the last titled King in Prussia and declared himself King
of Prussia after achieving full sovereignty for all historical Prussian lands.
Prussia had greatly increased its territories and became a leading military
power in Europe under his rule. He became known as Frederick the Great
(Friedrich der Große) and was affectionately nicknamed Der Alte Fritz ("Old
Fritz") by the Prussian people.

кошка

   -b, --number-nonblank
          number nonempty output lines, overrides -n

сгиб

   -s, --spaces
          break at spaces

   -w, --width=WIDTH
          use WIDTH columns instead of 80
4
ответ дан 23 November 2019 в 08:38

Другие вопросы по тегам:

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