Copy first n lines in linux

Linux Copy File Command [ cp Command Examples ]

cp Command Syntax

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Terminal app/Shell prompt
Est. reading time 3 mintues

The syntax is as follows to copy files and directories using the cp command:
cp SOURCE DEST
cp SOURCE DIRECTORY
cp SOURCE1 SOURCE2 SOURCE3 SOURCEn DIRECTORY
cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE DIRECTORY
Where,

  • In the first and second syntax you copy SOURCE file to DEST file or DIRECTORY.
  • In the third syntax you copy multiple SOURCE(s) (files) to DIRECTORY.

Note: You need to type the cp command at the dollar sign ($) prompt. This prompt means that the shell is ready to accept your typed commands. Do not type the dollar ($) sign. You need to open the Terminal app to use cp command on a Linux.

Linux Copy File Examples

To make a copy of a file called file.doc in the current directory as newfile.doc, enter:
$ cp file.doc newfile.doc
$ ls -l *.doc
Sample outputs:

You can copy multiple files simultaneously into another directory. In this example, copy the files named main.c, demo.h and lib.c into a directory named backup:
$ cp main.c demo.h libc. backup
If backup is located in /home/project, enter:
$ cp main.c demo.h libc. /home/project backup

Copy a file to another directory

To copy a file from your current directory into another directory called /tmp/, enter:
$ cp filename /tmp
$ ls /tmp/filename
$ cd /tmp
$ ls
$ rm filename

Verbose option

To see files as they are copied pass the -v option as follows to the cp command:

Preserve file attributes

To copy a file to a new file and preserve the modification date, time, and access control list associated with the source file, enter:
$ cp -p file.txt /dir1/dir2/
$ cp -p filename /path/to/new/location/myfile
This option ( -p ) forces cp to preserve the following attributes of each source file in the copy as allowed by permissions:

  1. Modification time/date
  2. Access time
  3. File flags
  4. File mode
  5. User ID (UID)
  6. Group ID (GID)
  7. Access Control Lists (ACLs)
  8. Extended Attributes (EAs)

Copying all files

The star wildcard represents anything i.e. all files. To copy all the files in a directory to a new directory, enter:
$ cp * /home/tom/backup

The star wildcard represents anything whose name ends with the .doc extension. So, to copy all the document files (*.doc) in a directory to a new directory, enter:
$ cp *.doc /home/tom/backup

Recursive copy

To copy a directory, including all its files and subdirectories, to another directory, enter (copy directories recursively):
$ cp -R * /home/tom/backup

Linux copy file command with interactive option

You can get prompt before overwriting file. For example, if it is desired to make a copy of a file called foo and call it bar and if a file named bar already exists, the following would prompt the user prior to replacing any files with identical names:
cp -i foo bar

  • 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

Verbose output with cp command

If you pass the -v to the cp, it makes tells about what is going on. That is verbose output:
cp -v file1 file2
cp -avr dir2 /backups/

Conclusion

This page explained cp command that is used for copying files under Linux and Unix-like systems. For more info see man pages: ls(1).

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

Источник

BASH Prepend A Text / Lines To a File

As far as I know there is no prepend operator on a bash or any other shell, however there are many ways to do the same. You can use ed, sed, perl, awk and so on to add text to the beginning of a file in Bash under Linux or Unix-like systems.

Bash prepend a text using a temporary file

Here is simple solution using a temporary file to prepend text:

Here is one line solution:

Prepending A Text or Lines To a File Under Linux and Unix

Using bash only solution to add text to the beginning of a file

No need to create a temp file. The syntax is:

To add multiple lines:

For example add text to the beginning of a text file called input using bash as follows:

  • 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

Use sed command to prepend data to a text file

The syntax is follows to prepend A text or lines to a file when we use the sed command:

Here is a sample input file:

Next prepend two lines (make sure you add \n ):

How do I prepend a string to the beginning of each line in a file?

The awk command syntax is:

Display result using the [nicmd name=”cat”] or grep command/egrep command:
$ cat output.txt
The sed syntax is:

Examples

Here is our sample file:

Use the sed or awk as follows:

Conclusion

You learned how to prepend a text or lines to a file when using bash and other command-line utilities. See sed,awk, and bash command man pages for more info using the man command:
$ man bash
$ man sed
$ man awk

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

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

perl -p -i -e ‘BEGIN < print "First line\n" >‘ originalfile

should work without needing an explicit temp file

If you’re going to use these commands in a script, though, “man mktemp” first.

Even simpler would be:
sed -i ‘1i Prepended line’ /tmp/newfile

+1 This works very nice and without using temporally files.

Works, but it _does_ use a temporary file behind the covers.
The following is from the info document:
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

nikolocalhost Aug 1, 2011 @ 21:28

That works on linux but not in solaris (unless you install gsed package), because de solaris sed command doesnt support “in place option” -i.

echo «text»|cat — yourfile > /tmp/out && mv /tmp/out yourfile

Thanks for help 🙂

Yes it does. The ` -i ` option is a mandatory part of POSIX, so it will work on any UNIX that takes itself seriously, Solaris included.

It just works differently, i.e. GNU sed allows you to omit the argument of the `-i` flag, as was done in the example, whereas most other seds require it.

sed -i.bak ‘1i Prepended line’ /tmp/newfile

Now hang your head in shame.

Ok, I was wrong on the POSIX part, I will hang my head in shame.

..but the missing flag argument is probably still the reason the example didn’t work on Solaris.

Yes, that worked very nicely for me in Linux armel 2.6.32-rc5, sed is great but if you don’t use it regularly for a month it’s RTFM every time. Thanks.

Excellent suggestion with `sed` very good.

You can also use tac (cat backwards) to make it work. It will print the file from end to beginning.

Thread’s old, I know, but I wanted to note that tac — at least in the version I have in Cygwin, is not fully “cat in reverse” alas.

As you say, it’ll print from the end — but it won’t take an argument like this:

Just thought I’d note that for others who might be searching the same issue as the OP.
This seems like such an obviously useful utility it’s unbelievable what a pita it is.

I tried the perl command (same one suggested to me by someone on IRC) and it didn’t work. It just printed to stdout and left the file unchanged. I’m kind of surprised two different people suggested the exact same non-working command, so I must be doing something wrong. What could I be doing wrong though??

I like the sed command, but I needed to add more than one line (and my text contained special characters).

This worked for me:

I’m not even really sure how it works, I just combined bits of code from a couple of random scripts I saw elsewhere. I should learn more sed 😛

this also worked:

tac your_file prepended_text | tac > your_new_file

tac does not add a damn thing.
Given this command:

— I get the error
tac: cannot open `thisistext’ for reading: No such file or directory.
Considering it’s a close cousin of cat, I shouldn’t expect it to do any more, logically.
Please do the newbie world a favour and remove any references to tac in this thread.

You need to put your prepend data into the file “thisistext”. Also, unless you want your file to come out upside down, you’ll have to pipe the output from the first tac into a second tac before redirecting to a file.

With a little creative use of shell commands, you can avoid needing a second input file. Passing ‘-‘ as an argument tells most tools to use standard input or output (whichever applies) as a file.

echo «my_prepend_text_goes_here» | tac biglist.txt — | tac > biglist5.txt

There are a couple of tricks where you can avoid needing to create biglist5.txt in the process (storing results to a variable or using “tee” to write your output), but I can’t find anything that will work on large files.

This is clever; even simpler, you can use
echo “prepend this” | cat – file.txt > newfile.txt

How about a command or script to add the same text to every line OF a file, not just to the file itself.

Believe it or not
bash prepend same text to beginning of all lines of file
does not have an exact match on Google. Ask.com and Yahoo! were sloppy with it (read:inexact and wide of the mark ultimately). Just more proof to my assertion that the world is going stupid.

This can be done with sed in place (a pretty scary operation):

sed -i -e ‘s/^/PREFIX/’ file_with_lines_to_prefix.txt

Thanks, Q. I’ve attempted something similar in the past without success.

This perl one-liner will prefix (not prepend, which isn’t a word) a line to the beginning of a file.

perl -pi -e ‘print «Put before first line\n» if $. == 1’ inFile.txt

(from the perl FAQ):

It’s also in the Merriam-Webster Unabridged Dictionary, which is more authoritative at the cost of a subscription, and it’s even a command in the popular jQuery javascript library. However, I agree prefix would be more proper English if one cares and has an educated audience that would not be confused.

You’ll have to copy and paste the url, as the link parser cannot handle it.

‘prepend’ is a corollary to ‘append’, which is an English word.

Ugh, my original message totally got garbled…

What the above SHOULD look like:

This can be used to insert a file into any line but the last one into a second file. For instance, to insert file1 into file2 at line 10:

Edited by Admin – added formatting html tags

You could generate a patch file and use patch.

That got completely mangled. Is there any way to protect my comments?

My finally correct version (may I request a preview feature?):

Another method is using ed:

echo -e “0a\nmy data goes here and ends at the period.\n.\n,wq” | ed myfile

A variation on this is:

echo “0r header.txt
w” | ed myfile.txt

Thanks, works well…

This is the best (sed) one-liner that I found for this problem:

sed -i -e ‘1i TEXT’ FILE

Above command will insert string TEXT into the first line of the file FILE.

echo «MAINCARD_MSISDN,SUB_SOC,EXPIRY_DATE,S,U,» | cat — $spoolFile > /tmp/out && mv /tmp/out $spoolFile

that line above works for. problem is if a have to run the script more than once. it will insert the same line again.. Any way to stop it?

Its worth mentioning that

echo -e «DATA-Line-1\n$(cat input)» > input

Is very ineficient and works only for small files, the larger files (e.g. 800Mb) crash the terminal and leave the file empty.

echo -e «DATA-Line-1\n$(cat input)» > input

dose not always work

This is the only sed syntax that works for me on OSX Sierra:

sed -i_bak ‘1s;^;prepended text ;’ test.file

Thanks, I’d been looking for an hour.

Thanks, this pointed me to just what I needed! I wanted to point out that your “Bash Only” way doesn’t need to be bash only – instead of using $(cat input) , use `cat input` (use the backtick character). It does the same thing as $() in bash, but it works in most shells 😀

Thank you
sed -i ‘1s;^;DATA-Line-1\n;’ input ” worked great!
Just what I needed

Источник

Читайте также:  Dns windows принцип работы
Оцените статью