Нумерация абзацев с помощью команды «cat»

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

Пример:

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.)

1
задан 8 September 2016 в 22:11

4 ответа

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

Вы можете указать все непустые строки в файле, используя 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 May 2018 в 06:20

Если в «параграфах» вы подразумеваете блоки строк, разделенных пустыми строками, вы можете добавить нумерацию с помощью простой команды 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 May 2018 в 06:20
  • 1
    Это не имеет пронумерованных строк и удаляет пустые строки с вывода. – Byte Commander 8 September 2016 в 16:36
  • 2
    Было бы полезно показать OP перенаправление для отправки этого вывода в другой файл. – Arronical 8 September 2016 в 16:36
  • 3
    @ByteCommander: OP ничего не говорит о отступов ненумерованных строк – user000001 8 September 2016 в 16:40
  • 4
    Да, он этого не делает. И, глядя на пример, который он только что предоставил, возможно, он просто хочет cat -n, так как все его «абзацы» это просто длинные строки ... – Byte Commander 8 September 2016 в 16:48
  • 5
    +1, поскольку ОП не был полностью ясен о том, как определенно нужен кот в исходной версии вопроса. – Arronical 8 September 2016 в 17:06

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

Нам нужно пронумеровать строки, а затем сделать их в параграфы. Для этого вы можете использовать fold. [!d1 ]

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.

cat

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

fold

   -s, --spaces
          break at spaces

   -w, --width=WIDTH
          use WIDTH columns instead of 80
4
ответ дан 23 May 2018 в 06:20

Я не знаю команды «параграф». cat -b - это то, что вы хотите использовать.

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

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

0
ответ дан 23 May 2018 в 06:20

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

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