Linux print first line

Содержание
  1. Linux / Unix: Display First Line of a File
  2. Syntax
  3. Example: Displaying the first line
  4. A note about sed command
  5. How to Skip the First Line of a File Using `awk`
  6. Create a text file
  7. Example 1: Skip the first line of a file using NR and the ‘>’ operator
  8. Example 2: Skip the first line by using NR and the ‘!=’ operator
  9. Example 3: Skip the first line of a file by using a conditional statement
  10. Example 4: Print the book names from the file but skip the first line
  11. Example 5: Format the file content after skipping the first line
  12. Example 6: Print the book names after skipping the first line using NR and NF
  13. Example 7: Print the formatted author names after skipping the first line
  14. Conclusion
  15. About the author
  16. Fahmida Yesmin
  17. Your Own Linux.
  18. Linux How To’s | Bash Scripting | Python
  19. Sunday, 12 April 2015
  20. Sed Command in Linux — Print Lines in a File
  21. Printing Lines from a File using sed
  22. A. sed — Print Lines with Line Number
  23. 1. Print ‘N’th line
  24. 2. Print all Lines starting from ‘M’th up to ‘N’th
  25. 3. Print Every ‘N’th Line Starting from ‘M’th Line
  26. B. sed — Print Lines with Regular Expression/Pattern
  27. 1. Print lines containing a Pattern
  28. 2. Print lines excluding a Pattern
  29. 3. Print Block of lines starting from pattern matching line
  30. 4. Print Block of lines ending at pattern matching line
  31. 5. Print Block of lines between two Pattern matches
  32. How to Display Specific Lines of a File in Linux Command Line
  33. Display specific lines using head and tail commands
  34. Print a single specific line
  35. Print specific range of lines
  36. Use SED to display specific lines
  37. Use AWK to print specific lines from a file
  38. Unix Sed Tutorial: Printing File Lines using Address and Patterns
  39. Unix Sed Introduction
  40. Unix Sed Working methodology
  41. Printing Operation in Sed
  42. 5 Sed ADDRESS Format Examples
  43. Sed Address Format 1: NUMBER
  44. Sed Address Format 2: NUMBER1
  45. Sed Address Format 3: START,END
  46. Sed Address Format 4: ‘$’ Last Line
  47. Sed Address Format 5: NUMBER,$
  48. 6 Sed PATTERN Format Examples
  49. Sed Pattern Format 1: PATTERN
  50. Sed Pattern Format 2: /PATTERN/,ADDRESS
  51. Sed Pattern Format 3: ADDRESS,/PATTERN/
  52. Sed Pattern Format 4: /PATTERN/,$
  53. Sed Pattern Format 5: /PATTERN/,+N
  54. Sed Pattern Format 6: /PATTERN/,/PATTERN/
  55. If you enjoyed this article, you might also like..

Linux / Unix: Display First Line of a File

Syntax

Tutorial details
Difficulty level Easy
Root privileges No
Requirements None
Est. reading time 1m

head -1 filename

Example: Displaying the first line

Open the Terminal application and type the following command:
$ head -1 foo.txt
The following example will show first 3 lines from /etc/passwd file:
$ head -3 /etc/passwd
Sample outputs:

To print first 3 lines and number lines of files use nl command as follows:
$ head -3 /etc/passwd | nl
Sample outputs:

A note about sed command

You can use sed command as follows:
$ sed -n 1p foo.txt

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

For more information see man pages: nl(1).

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

How to Skip the First Line of a File Using `awk`

There are various uses of the `awk` command in Linux. For example, it can be used to print the content of a text file. The first line of many text files contains the heading of the file, and sometimes, the first line must be skipped when printing the content of the file. In this tutorial, we will show you how to accomplish this task by using the `awk` command.

Create a text file

To follow along with this tutorial, create a tab-delimited text file named booklist.txt with the following content. This file contains a list of books with their corresponding authors. In this tutorial, we will show you how to print different parts of this file after skipping the first line.

Cybersecurity with bash Paul Troncone, Carl Albing

Command Line Kung Fu Jason Cannon

Linux Command Line Travis Booth

Bash in easy steps Mike McGrath

Unix in easy steps Mike McGrath

Example 1: Skip the first line of a file using NR and the ‘>’ operator

The NR variable indicates the number of records in a file. The following `awk` command uses the NR variable to skip the first line of a file. The value of NR is 1 for the first line. The following command will print lines for which the NR value is greater than 1.

$ awk ‘(NR>1)’ booklist.txt

The following output will be produced after running the above commands. The output includes all lines other than the first line of the file.

Example 2: Skip the first line by using NR and the ‘!=’ operator

The following `awk` command is similar to that in the previous example. However, the ‘!=’ comparison operator is used here instead of ‘>’.

$ awk ‘NR!=1’ booklist.txt

The following output will be produced after running the above commands. The output shows all lines other than the first line of the file.

Example 3: Skip the first line of a file by using a conditional statement

The following `awk` command will print the lines of the file if the if statement is true. Here, the if statement will be true only when the NR value does not equal 1.

The following output will be produced after running the above commands. The output includes all lines except the first line of the file.

Example 4: Print the book names from the file but skip the first line

Two `awk` commands are used in this example to print all book names except the first. The `awk` command will read the first column from the file based on the field separator (\t) and send the output to the second `awk` command. The second `awk` command will print the desired output.

$ awk -F » \t » ‘‘ booklist.txt | awk ‘NR!=1

The following output will be produced after running the above commands. The output shows all the book names except for that of the first book.

Example 5: Format the file content after skipping the first line

The ‘-F’ option, NR variable, and printf function are used in the following `awk` command to generate formatted output after skipping the first line. The command will divide the file content into columns based on \t, and printf will print the first and second columns when the NR value is at least 2.

The following output will be produced after running the above commands. The output shows the formatted content of the file, excluding the first line of the file.

Example 6: Print the book names after skipping the first line using NR and NF

The following `awk` command uses the ‘-F’ option and NR and NF to print the book names after skipping the first book. The ‘-F’ option is used to separate the content of the file base on \t. NR is used to skip the first line, and NF is used to print the first column only.

$ awk -F ‘\t’ ‘NR>1 && NF=1’ booklist.txt

The following output will be produced after running the above commands. The output includes all the book names in the file except for that of the first book.

Example 7: Print the formatted author names after skipping the first line

The following `awk` command uses the ‘-F’ option and a conditional statement to print the author names after skipping the first line. Here, the NR value is used in the if condition. Here, “Author Name:\n\n” will be printed as the first line instead of the content from the first line. The author’s names from the file will be printed for the other values of NR.

The following output will be produced after running the above commands. The output shows the text, “Author Name:” with a newline, and all author names are printed except the first one.

Conclusion

The first line of a file can be skipped by using various Linux commands. As shown in this tutorial, there are different ways to skip the first line of a file by using the `awk` command. Noteably, the NR variable of the `awk` command can be used to skip the first line of any file.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Your Own Linux.

Linux How To’s | Bash Scripting | Python

Sunday, 12 April 2015

Sed Command in Linux — Print Lines in a File

This is the first article of the «Super sed ‘ Series», in which we will learn how to print lines in a file using line numbers and regular expressions.

Before we directly jump to the main content, every learner should know what sed is. Here is the brief introduction of the Super sed :

  • sed stand for Stream EDitor and it being based on the ed editor, it borrows most of the commands from the ed . It was developed by Lee E. McMahon of Bell Labs.
  • sed offers large range of text transformations that include printing lines, deleting lines, editing line in-place, search and replace, appending and inserting lines, etc.
  • sed is useful whenever you need to perform common editing operations on multiple lines without using ‘vi’ editor.
  • Whenever sed is executed on an input file or on the contents from stdin, sed reads the file line-by-line and after removing the trailing newline, places it in the «Pattern space», where the commands are executed on them after conditions (as in case of regex matching) are verified, and then printed on the stdout.

Printing Lines from a File using sed

Before we start, just remember two points:

  1. sed «p» command lets us print specific lines based on the line number or regex provided.
  2. sed with option -n will suppress automatic printing of pattern buffer/space. So, we would want to use this option. (Explained in later section)

For our better understanding, let us have a file sedtest.txt with contents as follows:

A. sed — Print Lines with Line Number

1. Print ‘N’th line

This will print ‘N’th line in the FILE.txt .

Example:
To print 1st line,

While, to print last line,

Let us see, what if we had not used option -n , what would have been the result.

You can easily see that 5th line is printed twice, one from pattern buffer/space and other is the result of sed ‘5p’ .

2. Print all Lines starting from ‘M’th up to ‘N’th

This will print the block of lines starting at line number M and ending at line number N .

Example:
To print 3rd line to 8th line.

Similarly, in order to print lines starting from 5th up to last line, you would run-

3. Print Every ‘N’th Line Starting from ‘M’th Line

This will print Mth line and every Nth line coming after that.

Example:
To print every alternate line staring from 2nd one.

B. sed — Print Lines with Regular Expression/Pattern

1. Print lines containing a Pattern

This will print the line that contains the pattern provided.

2. Print lines excluding a Pattern

This will print all those lines which do not contain the pattern provided.

3. Print Block of lines starting from pattern matching line

This will start printing the lines from the one where pattern matches, till ‘N’th line.

Of course, in order to print all the lines starting from pattern matching line till the end, you would use ‘/PATTERN/,$p’ as follows —

4. Print Block of lines ending at pattern matching line

This will start printing the lines starting from the ‘N’th line, till the one where pattern matches.

So, here, if you wish to start from first line and end at a line matching a pattern, you would use —

5. Print Block of lines between two Pattern matches

This will start printing lines from 1st pattern match till 2nd pattern match.

That was all about the first article on sed command. More articles on sed are coming soon. So, stay tuned. Of course, do not forget to share your feedback in the comment section below.

Источник

How to Display Specific Lines of a File in Linux Command Line

How do I find the nth line in a file in Linux command line? How do I display line number x to line number y?

In Linux, there are several ways to achieve the same result. Printing specific lines from a file is no exception.

To display 13th line, you can use a combination of head and tail:

Or, you can use sed command:

To display line numbers from 20 to 25, you can combine head and tail commands like this:

Or, you can use the sed command like this:

Detailed explanation of each command follows next. I’ll also show the use of awk command for this purpose.

Display specific lines using head and tail commands

This is my favorite way of displaying lines of choice. I find it easier to remember and use.

Use a combination of head and tail command in the following function the line number x:

You can replace x with the line number you want to display. So, let’s say you want to display the 13th line of the file.

Explanation: You probably already know that the head command gets the lines of a file from the start while the tail command gets the lines from the end.

The “head -x” part of the command will get the first x lines of the files. It will then redirect this output to the tail command. The tail command will display all the lines starting from line number x.

Quite obviously, if you take 13 lines from the top, the lines starting from number 13 to the end will be the 13th line. That’s the logic behind this command.

Now let’s take our combination of head and tail commands to display more than one line.

Say you want to display all the lines from x to y. This includes the xth and yth lines also:

Let’s take a practical example. Suppose you want to print all the the lines from line number 20 to 25:

Use SED to display specific lines

The powerful sed command provides several ways of printing specific lines.

For example, to display the 10th line, you can use sed in the following manner:

The -n suppresses the output while the p command prints specific lines. Read this detailed SED guide to learn and understand it in detail.

To display all the lines from line number x to line number y, use this:

Use AWK to print specific lines from a file

The awk command could seem complicated and there is surely a learning curve involved. But like sed, awk is also quite powerful when it comes to editing and manipulating file contents.

NR denotes the ‘current record number’. Please read our detailed AWK command guide for more information.

To display all the lines from x to y, you can use awk command in the following manner:

It follows a syntax that is similar to most programming language.

I hope this quick article helped you in displaying specific lines of a file in Linux command line. If you know some other trick for this purpose, do share it with the rest of us in the comment section.

Источник

Unix Sed Tutorial: Printing File Lines using Address and Patterns

Let us review how to print file lines using address and patterns in this first part of sed tutorial.

We’ll be posting several awesome sed tutorials with examples in the upcoming weeks.

Unix Sed Introduction

  • sed is a “non-interactive” stream-oriented editor. Since its an “non-interactive” it can be used to automate editing if desired.
  • The name sed is an abbreviation for stream editor, and the utility derives many of its commands from the ed line-editor (ed was the first UNIX text editor).
  • This allows you to edit multiple files, or to perform common editing operations without ever having to open vi or emacs.
  • sed reads from a file or from its standard input, and outputs to its standard output.
  • sed has two buffers which are called pattern buffer and hold buffer. Both are initially empty.

Unix Sed Working methodology

This is called as one execution cycle. Cycle continues till end of file/input is reached.

  1. Read a entire line from stdin/file.
  2. Removes any trailing newline.
  3. Places the line, in its pattern buffer.
  4. Modify the pattern buffer according to the supplied commands.
  5. Print the pattern buffer to stdout.

Printing Operation in Sed

Linux Sed command allows you to print only specific lines based on the line number or pattern matches. “p” is a command for printing the data from the pattern buffer.

To suppress automatic printing of pattern space use -n command with sed. sed -n option will not print anything, unless an explicit request to print is found.

Let us first create thegeekstuff.txt file that will be used in all the examples mentioned below.

5 Sed ADDRESS Format Examples

Sed Address Format 1: NUMBER

This will match only Nth line in the input.

# sed -n ‘N’p filename

For example, 3p prints third line of input file thegeekstuff.txt as shown below.

Sed Address Format 2: NUMBER1

N with “p” command prints every Nth line starting from line M.

# sed -n ‘M

2p prints every 2nd line starting from 3rd line as shown below.

Sed Address Format 3: START,END

M,N with “p” command prints Mth line to Nth line.

# sed -n ‘M,N’p filename

For example, 4,8p prints from 4th line to 8th line from input file thegeekstuff.txt

Sed Address Format 4: ‘$’ Last Line

$ with “p” command matches only the last line from the input.

# sed -n ‘$’p filename

For example, $p prints only the last line as shown below.

Sed Address Format 5: NUMBER,$

N,$ with “p” command prints from Nth line to end of file.

# sed -n ‘N,$p’ filename

For example 4,$p prints from 4th line to end of file.

6 Sed PATTERN Format Examples

Sed Pattern Format 1: PATTERN

PATTERN could be unix regular expression. The below command prints only the line which matches the given pattern.

# sed -n /PATTERN/p filename

For example, following prints the line only which matches the pattern “Sysadmin”.

Sed Pattern Format 2: /PATTERN/,ADDRESS


# sed -n ‘/PATTERN/,Np’ filename

For example, following prints lines which matches the pattern to Nth line, from input. 3rd line matches the pattern “Hardware”, so it prints from 3rd line to 6th line.

Sed Pattern Format 3: ADDRESS,/PATTERN/

It prints from the Nth line of the input, to the line which matches the pattern. If the pattern doesnt match, it prints upto end of the input.

# sed -n ‘N,/PATTERN/p’ filename

For example, 4th line matches the pattern “Security”, so it prints from 3rd line to 4th line.

Sed Pattern Format 4: /PATTERN/,$

It prints from the line matches the given pattern to end of file.

# sed -n ‘/PATTERN/,$p’ filename

Sed Pattern Format 5: /PATTERN/,+N

It prints the lines which matches the pattern and next N lines following the matched line.

# sed -n ‘/PATTERN/,+Np’ filename

For example, following prints the 5th line which matches the pattern /Storage/ and next two lines following /Storage/.

Sed Pattern Format 6: /PATTERN/,/PATTERN/

Prints the section of file between two regular expression (including the matched line ).

# sed -n ‘/P1/,/P2/p’ filename

For example, 5th line matches “Storage” and 8th line matches “Design”, so it prints 5th to 8th.

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook
  • Awk Introduction – 7 Awk Print Examples
  • Advanced Sed Substitution Examples
  • 8 Essential Vim Editor Navigation Fundamentals
  • 25 Most Frequently Used Linux IPTables Rules Examples
  • Turbocharge PuTTY with 12 Powerful Add-Ons

This is a great addition to my bag of tricks. I knew about grep to find patterns, but sed looks like a good way to fix things in multiple files. Thanks!

format #2
invalid command code

# sed -n ‘4,’p file
sed: 1: “4,p”: expected context address

oh, sorry, my mistake =)
# sed -n ‘4,$’p file

2’p thegeekstuff.txt
sed: invalid command code

2’p thegeekstuff.txt
works fine. (gsed = GNU sed)

# — variant for UNIX (non GNU) sed:

> sed -n ‘3,$’ thegeekstuff.txt
prints every 2nd line starting from 3rd

> sed -n ‘3,$’ thegeekstuff.txt
prints every 3rd line starting from 3rd

Useful link:
http://sed.sourceforge.net/sed1line.txt
awesome tricks with 1-line scripts for sed
(http://ant0.ru/sed1line.html – russian version of sed1line document)

However, in the very last example, the match is on ‘Design’, not on ‘Website’.

Usefull Article, thanks Ramesh…

Hi,
Very good tutorial. Really it helped me a lot. Thank u sooooooo much.

Very good tutorial for sed. Thank you very much.

For the below command the output is not being limited to N’th (6th) line.

$sed -n ‘/Sysadmin/,6p’ thegeekstuff.txt

1. Linux – Sysadmin, Scripting etc.
2. Databases – Oracle, mySQL etc.
3. Hardware
4. Security (Firewall, Network, Online Security etc)
5. Storage
6. Cool gadgets and websites
10.Windows- Sysadmin, reboot etc.
================================

Please let me know where i am doing wrong.

The given command will print the lines which matches for the word ‘Sysadmin’ to 6th line in a file (if available) . Since first line matches for the word ‘Sysadmin’ it prints the first line to 6th line. And 10th line (last) line also matches to the given word, so it prints.

These examples are very useful.
I wonder how to apply “sed” to print the following format.
input data output data
a1 b1 a1 b1 a3 b3 a5 b5 a1 b1 b3 b5
a2 b2 —-> a2 b2 a4 b4 a6 b6 —-> a2 b2 b4 b6
a3 b3
a4 b4
a5 b5
a6 b6

Thank you in advance 🙂

In an organisation one wants to know how many programmers are there. The employee data is stored in a file called ‘personnel’ with one record per employee. Every record has field for designation. How can sed be used to print only the records of all employees who are programmers ?

How to find last 10 lines if I don’t know size of file?

It’s helping a lot ……thank uuuuuuuuuuuuuu

Hi ramesh
whats wrong with this code?

=========
I want to use sed for printing a file line by line

sorry for foolish question
the answer is :

for ((i=1;i> newfile
done

for ((i=1;i doomhammer65ir November 27, 2011, 3:27 pm

Hi,
There are some problems I am facing with linux right now.
This is what I am doing to generate a cryptographic signature fron bash script….

step1. I encrypt a text : encrypt(bhavyakailkhurabhavyakailkhura) and get a encrypted string sdfghjklsdfghjklzxcvbnmghjkdfghjkzxcvbnmzxc
step2. I copy that string manually from mouse no commands used and append it with a file..

$ cat textfile.txt…
user=bhavya
signature=

step3. Using “sed” on text file I send text between “<” and “>” to another file bhavya.txt
step4. now when I try to decrypt bhavya.txt it say error in reading file. I checked the text is same as encrypted. When I copy original encrypted text in step 1 and decrypt It works.

I think the problem is sed command changes spacing between text its not same as copying using mouse. Do you have any idea how we can solve this problem?

Sorry for clumsy and lengthy explanation.

I would like to subsitute the comma in the amount enclosed in double quote only and leave all the comma as it. How can I do it?R,112074121151,45891,SMITH,JOHN ,HELLEN,”$1,078.67″,1118.69
Thank you.
Hedy

It’s very helpful to understand what sed is!.

i want to print the last 5 lines of a file using sed command.

hi., i want to know the syntax for printing multiple different lines using sed.
like sed -n ‘2,4’p,’6,8’p thegeekstuff.txt..
want to print lines 2 to 4 and 6 to 8., how to do it.

Rahul Prasad,
Try this command for emulating tail -5.
sed -e :a -e ‘$q;N;6,$D;ba’ thegeekstuff.txt

Shiva,
You can try this command.
sed -n ‘2,4 p; 6,8 p’ thegeekstuff.txt
or
sed -n -e ‘2,4 p’ -e ‘6,8 p’ thegeekstuff.txt

I just started learning sed and I am glad I found this article. You made it very illustrative with all the examples. Thank you

Hi All,
How to print 3th line first and 2nd line next??
3. Hardware
2. Databases – Oracle, mySQL etc.

Hi., i want to change the extension of my all files which are in current dir. via using sed command………….. , i m trying this code in a shell script
#!/bin/bash
for file in *
do
NEW=”echo $file|sed -f ‘s/.txt.new/.txt/g’”
mv $file $NEW
done

when i m running this shell script, o/p is :-
mv: target `\’s/txt.new/txt/g\” is not a directory

Plz fix it……………. thanx in advance………

has anyone got issues with

Sed Pattern Format 6: /PATTERN/,/PATTERN/
Prints the section of file between two regular expression (including the matched line ).

Источник

Читайте также:  Восстановление отсутствующего файла windows system32 config system
Оцените статью