Sponsored Content
Top Forums Shell Programming and Scripting How to use sed to replace the a string in the same file using sed? Post 302407978 by alister on Saturday 27th of March 2010 12:04:12 PM
Old 03-27-2010
Please excuse the pedantism ahead. Smilie

It depends on what exactly you mean by an intermediate file. If you simply mean that you don't want to manually create a backup copy to work with, then, sure, if available, sed -i or perl -pi will do the job. However, if you must edit a file in place, truly in place, without consuming an inode, you should probably use ed.

To substitute every occurrence of a string in a file:
Code:
printf '%%s/original/replacement/g\nw\nq\n' | ed -s file

Note the inode change after each command except ed:
Code:
$ echo editor > f; cat f;  ls -i f
editor
4636174 f
$ sed -i -e 's/.*/sed -i/' f; cat f; ls -i f
sed -i
4636175 f
$ perl -pi -e 's/.*/perl -pi/' f; cat f; ls -i f
perl -pi
4636176 f
$ printf 's/.*/ed/\nw\nq\n' | ed -s f; cat f; ls -i f
ed
4636176 f

On a related note, if there is no strict in-place requirement, you can have fun with open descriptors:
Code:
$ (rm f; sed 's/.*/open descriptor fun/' > f) < f
$ cat f; ls -i f
open descriptor fun
4636178 f

This works because the unlink system call used by rm will not delete a file's contents if any process has an open file descriptor pointing to it; it will remove the file's entry from its directory, but the data is still available so long as the descriptor is open. In the code above, the subshell holds an open file descriptor on "f" (thanks to the input redirection), so when rm unlinks "f", while the data is no longer reachable via the name "f", it is still available via standard input to all processes created by the subshell. When sed runs, it reads the data formerly known as "f", but since "f" is no longer linked in the directory, redirecting sed's standard output to "f" clobbers nothing. Refer to http://www.opengroup.org/onlinepubs/...ns/unlink.html for more info.

It goes without saying that, while cool, the unlink/open-descriptor trick is vulnerable to system failure. If the system crashes at just the right moment, it's possible for the filesystem to not have any link to any version of the data. But, hey, you only live once, right? Smilie

Regards,
Alister

Last edited by alister; 03-27-2010 at 01:26 PM..
 

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

How do i use sed to replace string with values from a dictionary file

I have file 1 with one million rows. one of the fields is "FIRSTNAME" (the string) I have a second file with about 20 first names. JUDE DAVID HOMER CANE ABEL MARTY CARL SONNY STEVE BERT OSCAR MICKY JAMES JOHN GLENN DOUG (3 Replies)
Discussion started by: yoyolandre
3 Replies

2. Shell Programming and Scripting

Using sed to replace a string in file with a string in a variable that contains spaces

Hi, i call my shell like: my_shell "my project name" my script: #!/bin/bash -vx projectname=$1 sed s/'PROJECT_NAME ='/'PROJECT_NAME = '$projectname/ <test_config_doxy >temp cp temp test_config_doxy the following error occurres: sed s/'PROJECT_NAME ... (2 Replies)
Discussion started by: vivelafete
2 Replies

3. Shell Programming and Scripting

replace (sed?) a single line/string in file with multiple lines (string) from another file??

Can someone tell me how I can do this? e.g: Say file1.txt contains: today is monday the 22 of NOVEMBER 2010 and file2.txt contains: the 11th month of How do i replace the word NOVEMBER with (5 Replies)
Discussion started by: tuathan
5 Replies

4. Shell Programming and Scripting

sed replace string in file with stdin

Hi Im trying to do the following: grep -H Date: out/* | sed 's/':'/ /' | awk '$4 ~ /^/ {print $1}' | while read VARIABLE; do awk '{print $1,$3,$2}' $VARIABLE | sed (take stdin and replace a string in $VARIABLE) done What this is basically doing is finding all files with Date: in... (11 Replies)
Discussion started by: duonut
11 Replies

5. Shell Programming and Scripting

replace (sed?) a string in file with multiple lines (string) from variable

Can someone tell me how I can do this? e.g: a=$(echo -e wert trewt ertert ertert ertert erttert erterte rterter tertertert ert) How do i replace the STRING with $a? I try this: sed -i 's/STRING/'"$a"'/g' filename.ext but this don' t work (2 Replies)
Discussion started by: jforce
2 Replies

6. Shell Programming and Scripting

How to replace a string containing @ in a file using sed ?

I have a list of names and email addresses. Sample File - username=poga--poga@yahoo.com new-york,US 512834 username=poga123--poga123@hotmail.com new-jersey,US 0894753 Requirement is to replace the email ids as dummy_username@xyz.com using sed only. Output File -... (4 Replies)
Discussion started by: poga
4 Replies

7. Shell Programming and Scripting

How to replace a string with a variable in a file using sed?

I have a file having some text like: PATH_ABC=/user/myLocation I have to replace "/user/myLocation" with a session variable say, $REPLACE_PATH, where $REPLACE_PATH=/user/myReplaceLocation The following sed command is not working. It is writing PATH_ABC=$REPLACE_PATH in the file ... (2 Replies)
Discussion started by: SKhan
2 Replies

8. Shell Programming and Scripting

sed - Replace string with file contents

Hello, I have two files: file1 and file2 file1 has the following info: --- host: "localhost" port: 3000 reporter_type: "zookeeper" zk_hosts: - "localhost:2181" file2 contains an IP address (1.1.1.1) What I want to do is replace localhost with 1.1.1.1, so that the... (4 Replies)
Discussion started by: Jay Kah
4 Replies

9. Shell Programming and Scripting

Replace string in XML file with awk/sed with string from another

Sorry for the long/weird title but I'm stuck on a problem I have. I have this XML file: </member> <member> <name>TransactionID</name> <value><string>123456789123456</string></value> </member> <member> <name>Number</name> ... (9 Replies)
Discussion started by: cozzin
9 Replies

10. Shell Programming and Scripting

Replace string of a file with a string of another file for matches using grep,sed,awk

I have a file comp.pkglist which mention package version and release . In 'version change' and 'release change' line there are two versions 'old' and 'new' Version Change: --> Release Change: --> cat comp.pkglist Package list: nss-util-devel-3.28.4-1.el6_9.x86_64 Version Change: 3.28.4 -->... (1 Reply)
Discussion started by: Paras Pandey
1 Replies
CLOSE(2)						     Linux Programmer's Manual							  CLOSE(2)

NAME
close - close a file descriptor SYNOPSIS
#include <unistd.h> int close(int fd); DESCRIPTION
close() closes a file descriptor, so that it no longer refers to any file and may be reused. Any record locks (see fcntl(2)) held on the file it was associated with, and owned by the process, are removed (regardless of the file descriptor that was used to obtain the lock). If fd is the last file descriptor referring to the underlying open file description (see open(2)), the resources associated with the open file description are freed; if the descriptor was the last reference to a file which has been removed using unlink(2) the file is deleted. RETURN VALUE
close() returns zero on success. On error, -1 is returned, and errno is set appropriately. ERRORS
EBADF fd isn't a valid open file descriptor. EINTR The close() call was interrupted by a signal; see signal(7). EIO An I/O error occurred. CONFORMING TO
SVr4, 4.3BSD, POSIX.1-2001. NOTES
Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota. A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a file system to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hardware at this point.) It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be reused, there are some obscure race conditions that may cause unintended side effects. SEE ALSO
fcntl(2), fsync(2), open(2), shutdown(2), unlink(2), fclose(3) COLOPHON
This page is part of release 3.25 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at http://www.kernel.org/doc/man-pages/. Linux 2007-12-28 CLOSE(2)
All times are GMT -4. The time now is 07:38 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy